Get field name when javax.validation.ConstraintViolationException is thrown

谁说胖子不能爱 提交于 2019-12-09 08:49:21

问题


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;
}

回答1:


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



回答2:


use this method(ex is ConstraintViolationException instance):

Set<ConstraintViolation<?>> set =  ex.getConstraintViolations();
    List<ErrorField> errorFields = new ArrayList<>(set.size());
    ErrorField field = null;
    for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) {
        ConstraintViolation<?> next =  iterator.next();
       System.out.println(((PathImpl)next.getPropertyPath())
                .getLeafNode().getName() + "  " +next.getMessage());


    }



回答3:


If you inspect the return value of getPropertyPath(), you'll find it'a Iterable<Node> and the last element of the iterator is the field name. The following code works for me:

// I only need the first violation
ConstraintViolation<?> violation = ex.getConstraintViolations().iterator().next();
// get the last node of the violation
String field = null;
for (Node node : violation.getPropertyPath()) {
    field = node.getName();
}



回答4:


I had the same problem but also got "sayHi.arg0" from getPropertyPath. I chose to add a message to NotNull annotations since they were part of our public API. Like:

 @NotNull(message = "timezone param is mandatory")

you can obtain the message by calling

ConstraintViolation#getMessage()




回答5:


To get only parameter name which is last part of the Path.

violations.stream()
                .map(violation -> String.format("%s value '%s' %s", StreamSupport.stream(violation.getPropertyPath().spliterator(), false).reduce((first, second) -> second).orElse(null),
                        violation.getInvalidValue(), violation.getMessage())).collect(Collectors.toList());


来源:https://stackoverflow.com/questions/36555057/get-field-name-when-javax-validation-constraintviolationexception-is-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!