I have started using javax.validation's @Valid
annotation to validate data arriving at my REST endpoints. This is working as expected and throwing applicable exceptions:
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [org.<...>.crs.model.RegistrantEntity] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Email address is invalid', propertyPath=email, rootBeanClass=class org.<...>.crs.model.RegistrantEntity, messageTemplate='Email address is invalid'}
My understanding of the ExceptionMapper
is that i should be able to do this:
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException exception) {
return Response.status(Response.Status.BAD_REQUEST).entity(exception).build();
}
}
Which should catch that exception and specify an appropriate Response
object to send back.
This however is not working, here is the full top-level stacktrace items:
14:40:46,357 ERROR [org.jboss.as.ejb3.invocation] (default task-1) WFLYEJB0034: Jakarta Enterprise Beans Invocation failed on component AnswerResource for method public javax.ws.rs.core.Response org.<…>.crs.api.AnswerResource.updateAnswer(org.<…>.crs.api.model.Answer,java.util.UUID,java.lang.String) throws java.net.URISyntaxException,java.io.IOException: javax.ejb.EJBTransactionRolledbackException: javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction.
…
Caused by: javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction.
…
Suppressed: javax.transaction.RollbackException: WFTXN0061: Transaction is marked rollback-only
…
Suppressed: javax.transaction.RollbackException: WFTXN0061: Transaction is marked rollback-only
…
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [org.<…>.crs.model.RegistrantEntity] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Email address is invalid', propertyPath=email, rootBeanClass=class org.<…>.crs.model.RegistrantEntity, messageTemplate='Email address is invalid'}
]
My understanding is that the ConstraintViolationException
, while being the cause, has been packaged in the RollbackException and as such is not caught by ExceptionMapper.
- Can someone confirm this?
- If so, is there a way to override this behavior and catch any exception containing a
ConstraintViolationException
inside it? - If not, what would be a good work around?
Thoughts?
Thanks.