I am developing a Spring Boot based REST API. I am validating the input entities using custom ConstraintValidator annotations. My problem is that I cannot return the ConstraintViolationException messages in the response. My exception handler does not catch the exceptions (maybe because they're wrapped in another types of exceptions).
Can I please get some advice on how to handle the situation?
I've searched all over the Internet but I couldn't find a fitting solution for me and I've also wasted some hours doing so.
Example annotation:
@Documented
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
@Constraint(validatedBy = BirthDateValidator.class)
public @interface ValidBirthDate {
String message() default "The birth date is not valid.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator class:
public class BirthDateValidator extends FieldValidationBase implements ConstraintValidator<ValidBirthDate, LocalDate> {
private static final Logger LOGGER = LoggerFactory.getLogger(BirthDateValidator.class);
@Override
public void initialize(ValidBirthDate constraintAnnotation) {
}
@Override
public boolean isValid(LocalDate birthDate, ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
LOGGER.info("Starting the validation process for birth date {}.", birthDate);
if(birthDate == null) {
constraintValidatorContext.buildConstraintViolationWithTemplate("The birth date is null.")
.addConstraintViolation();
return false;
}
//other validations
return true;
}
Model class:
public class Manager extends BaseUser {
//other fields
@Valid
@ValidBirthDate
private LocalDate birthDate;
//setters & getters
Exception handler:
@ExceptionHandler(value = ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) {
List<String> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + ": " + violation.getMessage());
}
Error response = new Error(errors);
return new ResponseEntity<Object>(response, new HttpHeaders(), BAD_REQUEST);
}
The controller:
@RestController
@RequestMapping(value = "/register", consumes = "application/json", produces = "application/json")
public class RegistrationController {
@Autowired
private RegistrationService registrationService;
@PostMapping(value = "/manager")
public ResponseEntity registerManager(@RequestBody @Valid Manager manager) {
registrationService.executeSelfUserRegistration(manager);
return new ResponseEntity<>(new Message("User " + manager.getEmailAddress() + " registered successfully!"), CREATED);
}
}
I get the 400 response code, but I am not seeing any response body containing the violated constraint messages.
Exception
), but that doesn't catch it either. I assume the exception is handles internally by Spring and wrapped into something else, but I have no idea what that is. Shouldn't theConstraintViolationException
be thrown when the object fails the validation (isValid()
returns false)? – PronouncementbirthDate
is null? – Lambdacism