引发javax.validation.ConstraintViolationException时获取字段名称 [英] Get field name when javax.validation.ConstraintViolationException is thrown
本文介绍了引发javax.validation.ConstraintViolationException时获取字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当PathVariable的名称"未通过验证时,将引发javax.validation.ConstraintViolationException.有没有办法在抛出的javax.validation.ConstraintViolationException中检索参数名称?
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;
}
推荐答案
以下异常处理程序展示了其工作原理:
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);
}
您可以使用
constraintViolation.getInvalidValue()
您可以使用
constraintViolation.getPropertyPath()
这篇关于引发javax.validation.ConstraintViolationException时获取字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文