JSR 303 ConstraintViolationException 和详细消息
JSR 303 ConstraintViolationException and detailed message
我已经为 Spring Boot 1.5.1
应用程序配置了 JSR 303
验证。现在我得到 ConstraintViolationException
以防数据错误。
是否可以通过 ConstraintViolationException
获得有关错误信息(例如哪个字段或方法参数违反约束)的详细消息(现在为空)?
嗯,您的 ConstraintViolationException
有一组 ConstraintViolation
个对象。他们每个人都有你想要的细节。
public static <T> String getValidationMessage(ConstraintViolation<T> violation) {
String className = violation.getRootBeanClass().getSimpleName();
String property = violation.getPropertyPath().toString();
//Object invalidValue = violation.getInvalidValue();
String message = violation.getMessage();
return String.format("%s.%s %s", className, property, message);
}
有了这个,我会收到一条消息,例如 "OrderLine.quantity must be greater than 0"
我已经为 Spring Boot 1.5.1
应用程序配置了 JSR 303
验证。现在我得到 ConstraintViolationException
以防数据错误。
是否可以通过 ConstraintViolationException
获得有关错误信息(例如哪个字段或方法参数违反约束)的详细消息(现在为空)?
嗯,您的 ConstraintViolationException
有一组 ConstraintViolation
个对象。他们每个人都有你想要的细节。
public static <T> String getValidationMessage(ConstraintViolation<T> violation) {
String className = violation.getRootBeanClass().getSimpleName();
String property = violation.getPropertyPath().toString();
//Object invalidValue = violation.getInvalidValue();
String message = violation.getMessage();
return String.format("%s.%s %s", className, property, message);
}
有了这个,我会收到一条消息,例如 "OrderLine.quantity must be greater than 0"