Issue
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.
Solution
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
Answered By - Question_Everything
Answer Checked By - Candace Johnson (JavaFixing Volunteer)