如何在约束违规列表中展开、提取、约束违规异常?

How to unwrap, extract, constraint violations exceptions in a list of constraint violations?

我不太确定如何问这个问题,但我有一个客户 class,我在其上创建了一个带有注释的自定义验证器,并在验证器 class 中实现了 ConstraintValidator。它工作得很好,但显然在抛出时,它被包裹在其他异常中。但是得到根本原因我得到了这个:

javax.validation.ConstraintViolationException: Validation failed for classes [vidleytake4.data.entity.Customer] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='Customer must be 18 years old to become a member', propertyPath=, rootBeanClass=class se.soccan.vidleytake4.data.entity.Customer, messageTemplate='Customer must be 18 years old to become a member'}
]

当然,我想通过界面向用户显示插入的消息,但这种情况始于 med 能够将其从该列表中删除,一些不同的方法并没有让我更接近,20- or-so google 会议也没有帮助,所以我愿意接受建议......我调查了异常处理程序,并没有真正理解它们,并试图检查我的咳嗽 TransactionSystemException根本原因是使用 NestedExceptionUtils.getRootcause(e) 运气不佳...

的 ConstraintViolationExceotion 实例

TransactionSystemException 应该包含根本原因:TransactionSystemException.getRootCause()

如果这不是根本原因,您可能需要反复检查原因。

List<String> violationMessages;
for (Exception exception : exceptionList) {
    if (exception instanceof ConstraintViolationException) {
        ConstraintViolationException constraintEx = ((ConstraintViolationException) exception);
        Set<ConstraintViolation<?>> violations = constraintEx.getConstraintViolations();
        // do something with violations, for example:
        violationMessages = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        break;
    }
}

帮手:ExceptionUtils.getThrowableList(ex)