Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the payload property from bean validation annotation

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()).

like image 473
Paulo Pedroso Avatar asked Mar 31 '16 20:03

Paulo Pedroso


People also ask

What does @NotNull annotation Bean in Bean property?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true.

What does @validated annotation do?

The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. We'll learn more about how to use it in the section about validating path variables and request parameters.

What is @email annotation in spring boot?

@Email annotation is part of javax. validation. constraints package. Using Just @Email annotation like below @Data.

What is @valid annotation in spring boot?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.


1 Answers

Assuming your starting point is a ConstraintViolationException you are getting the set of ConstraintViolation instances via getConstraintViolations().

Each ConstraintViolation then has a getConstraintDescriptor(), which gives you metadata about the failing constraints. Once you have the ConstraintDescriptor you just call getPayload().

like image 123
Hardy Avatar answered Sep 24 '22 22:09

Hardy