抛出javax.validation.ConstraintViolationException时获取字段名称

Jos*_*osh 15 spring bean-validation

当PathVariable'name'未通过验证时,将抛出javax.validation.ConstraintViolationException.有没有办法在抛出的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;
}
Run Code Online (Sandbox Code Playgroud)

leo*_*ang 16

如果您检查 的返回值getPropertyPath(),您会发现 it'aIterable<Node>并且迭代器的最后一个元素是字段名称。以下代码对我有用:

// 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();
}
Run Code Online (Sandbox Code Playgroud)

  • javax.validation.Path.Node (7认同)

Ste*_*com 11

以下异常处理程序显示它是如何工作的:

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

}
Run Code Online (Sandbox Code Playgroud)

您可以使用访问无效值(名称)

 constraintViolation.getInvalidValue()
Run Code Online (Sandbox Code Playgroud)

您可以使用访问属性名称'name'

constraintViolation.getPropertyPath()
Run Code Online (Sandbox Code Playgroud)

  • 我试过了,但getPropertyPath返回sayHi.arg0 (13认同)

小智 7

使用此方法(例如是 ConstraintViolationException 实例):

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


    }
Run Code Online (Sandbox Code Playgroud)


rav*_*iru 5

只获取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());
Run Code Online (Sandbox Code Playgroud)