I have a class with validation annotations on my properties, like this one:
@NotNull(payload = INVALID_CATEGORY_DESCRIPTION.class)
@Size(min = 1, max = 255, payload = INVALID_CATEGORY_DESCRIPTION_LENGHT.class)
private String description;
Then I have a @ControllerAdvice to handle validation exceptions.
@ResponseStatus(BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
When one or more validation annotation fail, the exception handler is triggered as expected.
In order to get the payload property from the annotations, I am iterating over the fields with validation errors, then over the annotations and only then comparing the annotation name with the FieldError code. With the annotation in hands I can access the payload.
I wonder if there is a more elegant way to get the payload or the annotation which triggered the exception, as there is for the message property (exception.getMessage()).