Issue
I have an api that validates and creates user. When I don't type email in request's body I receive
{
"timestamp": "2020-11-26T13:55:40.116+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='user'. Error count: 1",
"path": "/api/users"
}
I want to change message to more understable error like "email must be not null". That's how my model's property looks:
@NotNull
private String email;
And here is my controller's method:
@PostMapping("/users")
public ResponseEntity<User> addUser(@RequestBody @Valid User user) {
User savedUser = manager.save(user);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.ok(savedUser);
}
I've tried to set custom message in @NotNull
annotation, but the message doesn't change. Also when the error gets thrown console shows this message:
2020-11-26 15:09:11.460 WARN 7137 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<pl.vemu.socialApp.entities.User> pl.vemu.socialApp.controllers.UserController.addUser(pl.vemu.socialApp.entities.User) throws pl.vemu.socialApp.exceptions.user.UserWithEmailAlreadyExistException: [Field error in object 'user' on field 'email': rejected value [xsars.pl]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@2a50b33,.*]; default message [must be a well-formed email address]] ]
How to set the message in response json?
How to get rid of this message in console? Other errors don't show message in console.
Solution
The problem is that Spring by default doesn't send errors while binding. To enable it you have to add server.error.include-binding-errors=always
in your application.properties.
Answered By - Vemu
Answer Checked By - Marilyn (JavaFixing Volunteer)