6

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.

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

3
@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);
}

Comments

1

Simple solution using stream():

...
catch (MethodArgumentNotValidException ex) {
    message = ex.getFieldErrors()
        .stream()
        .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
        .collect(Collectors.joining("; "));
}
...

Comments

0
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    return new ResponseEntity<Object>(ex.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
}

Comments

0
import org.springframework.context.support.DefaultMessageSourceResolvable;

public ResponseEntity handleValidationException(MethodArgumentNotValidException ex)
{
    List<String> errorMessages = ((MethodArgumentNotValidException)ex)
            .getBindingResult()
            .getFieldErrors().stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.toList());
    return new ResponseEntity(errorMessages.toString(), HttpStatus.BAD_REQUEST);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.