Display only default message of Spring boot validation - MethodArgumentNotValidException

Viewed 4078

How can i strip down the excessive information from MethodArgumentNotValidException and keep only the required "default message" ??

I am experimenting with Validation annotations- @NotNull, @NotBlank, and @NotEmpty

I have configured a custom error message as below:-

@NotNull(message = "Aaaah !!!! firstname cannot be empty !!!")
private String firtName;

My Exception handler is :-

@RestControllerAdvice
public class ControllerAdviceClass {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity handleValidationException(MethodArgumentNotValidException ex)
    {
        return new ResponseEntity(ex.getMessage() , HttpStatus.BAD_REQUEST);
    }
}

But the exception message i see on swagger is :-

Validation failed for argument [0] in public cosmosdb.User cosmosdb.CosmosController.postResult(cosmosdb.User): 
[Field error in object 'user' on field 'firstName': rejected value [null]; codes [NotNull.user.firstName,NotNull.firstName,NotNull.java.lang.String,NotNull];
 arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.firstName,firstName]; arguments []; default message [firstName]]; 
default message [Aaaah !!!! firstname cannot be empty !!!]] 

I want to see only the default message * [Aaaah !!!! firstname cannot be empty !!!]] * and remove the extra bunkum.

3 Answers

I had a similar experience with adjusting the default messages to something more meaningful.

You have to implement a javax.validation.MessageInterpolation interface. From there you'll be able to interpolate your default message.

I used this site as a reference to solve my issue. https://www.baeldung.com/spring-validation-message-interpolation

@Override
protected ResponseEntity<Object> 
handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    logError(ex, HttpStatus.BAD_REQUEST);
    Map<String, String> errorMap = new HashMap<>();
    ex.getBindingResult().getFieldErrors().forEach(error -> {
        errorMap.put(error.getField(),error.getDefaultMessage());
    });
    return new ResponseEntity<>(errorMap, HttpStatus.BAD_REQUEST);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    return new ResponseEntity<Object>(ex.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
}
Related