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

Viewed 371

I'm not exactly sure on how to ask this question but I have a customer class on which i created a custom validator with an annotation and implementing the ConstraintValidator in the validator class. It works perfectly, but obviously when thrown, it is wrapped pretty deep into other exceptions. But getting the rootcause I get this:

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'}
]

Of course I want to display that interpolated message to the user through the interface, but that kind of starts with med being able to get it out of that list a few different approaches have not gotten me any closer, 20-or-so google sessions haven't helped either so I'm open for suggestions... I looked into Exceptionhandlers, not understanding them really, and trying to check if my cought TransactionSystemException's root cause is an instance of ConstraintViolationExceotion by using NestedExceptionUtils.getRootcause(e)no luck...

1 Answers

TransactionSystemException should contain the root cause: TransactionSystemException.getRootCause()

If it's not the root cause, you may need to iterate over the causes.

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

Helpers: ExceptionUtils.getThrowableList(ex)

Related