Get field name when javax.validation.ConstraintViolationException is thrown

梦想与她 提交于 2019-11-30 11:39:09
Stefan Isele - prefabware.com

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

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


    }

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

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

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