Get field name when javax.validation.ConstraintViolationException is thrown

Josh picture Josh · Apr 11, 2016 · Viewed 21.3k times · Source

When the PathVariable 'name' doesn't pass validation a javax.validation.ConstraintViolationException is thrown. Is there a way to retrieve the parameter name in the thrown javax.validation.ConstraintViolationException?

@RestController
@Validated
public class HelloController {

@RequestMapping("/hi/{name}")
public String sayHi(@Size(max = 10, min = 3, message = "name should    have between 3 and 10 characters") @PathVariable("name") String name) {
  return "Hi " + name;
}

Answer

The following Exception Handler shows how it works :

@ExceptionHandler(ConstraintViolationException.class)

ResponseEntity<Set<String>> handleConstraintViolation(ConstraintViolationException e) {
    Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();

Set<String> messages = new HashSet<>(constraintViolations.size());
messages.addAll(constraintViolations.stream()
        .map(constraintViolation -> String.format("%s value '%s' %s", constraintViolation.getPropertyPath(),
                constraintViolation.getInvalidValue(), constraintViolation.getMessage()))
        .collect(Collectors.toList()));

return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);

}

You can access the invalid value (name) with

 constraintViolation.getInvalidValue()

You can access the property name 'name' with

constraintViolation.getPropertyPath()