'"Validation failed for object='user'. Error count: 1" instead of "email must not be null"
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 1:[1]
Instead of relying on "message" property, you can use "defaultMessage" property.
You can set a custom error message on @NotNull annotation.
@NotNull(message = "Name cannot be null")
private String name;
@NotNull(message = "email cannot be null")
@NotEmpty(message = "email cannot be empty")
private String email;
If validation fails for a field, spring will set these custom messages on "defaultMessage" property
As you said in the comments that you couldn't find defaultMessage, another approach (perhaps the dirty approach) would be to manually create the response body, you can refer the following sample code to build it:
@PostMapping("saveEmployee")
public ResponseEntity<?> eat(@RequestBody @Valid Employee employee, Errors errors) {
if (errors.hasFieldErrors()) {
FieldError fieldError = errors.getFieldError();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(fieldError.getDefaultMessage());
}
return ResponseEntity.ok(employee);
}
FieldError#getDefaultMessage() will expose the value of message attribute in @NotNull(message = "email can't be null")
Solution 2:[2]
ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("email must be not null");
and replace HttpStatus.UNPROCESSABLE_ENTITY with a suitable error code.
Solution 3:[3]
use also @Validated at class level plus use a custom error handler like this
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) {
String violations = e.getConstraintViolations().stream().map(cv -> cv.getConstraintDescriptor().getMessageTemplate()).toList().toString();
return new ResponseEntity<>
("not valid due to validation errors: " + violations, HttpStatus.BAD_REQUEST);
}
}
Solution 4:[4]
You can override default error messages in BindException.
@ControllerAdvice
public class BindExceptionHandler {
@ExceptionHandler(BindException.class)
@ResponseBody
public String handleBindExceptionHandler(BindException exception) {
return "Your message like 'email must be not null'";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | codebrane |
| Solution 3 | Salvatore Pannozzo Capodiferro |
| Solution 4 | Green Lei |
