I have the following POJO:
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) throws DataFormatException {
if(name.equals(""))
{
throw new DataFormatException("Mpla Mpla");
}
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonCreator
public User(@JsonProperty("name") String name, @JsonProperty("email") String email,@JsonProperty("username") String username,@JsonProperty("password") String password) throws DataFormatException {
setName(name);
this.email = email;
this.username = username;
this.password = password;
}
}
And the following controller:
public class MainController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
}
@PostMapping(path="/add") // Map ONLY POST Requests
public @ResponseBody String addNewUser (@RequestBody @Valid User user1) {
// @ResponseBody means the returned String is the response, not a view name
userRepository.save(user1);
return "Saved";
}
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
The problem is that instead of producing the error DataFormatException it produces:
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not construct instance of hello.Users.User, problem: Mpla Mpla; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of hello.Users.User, problem: Mpla Mpla\n at [Source: java.io.PushbackInputStream@7604dc21; line: 6, column: 1]",
Although as can be seen above the problem is correct but the message is wrong. So what can be done in order to produce the wanted error and not the one produced by Jackson?