我已经开始使用 javax.validation 的@Valid
注释来验证到达我的 REST 端点的数据。这是按预期工作并引发适用的异常:
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'}
我的理解ExceptionMapper
是我应该能够做到这一点:
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();
}
}
Response
哪个应该捕获该异常并指定要发回的适当对象。
然而,这不起作用,这是完整的顶级堆栈跟踪项:
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'}
]
我的理解是ConstraintViolationException
,虽然是原因,但已被打包在 RollbackException 中,因此不会被 ExceptionMapper 捕获。
- 有人可以证实这一点吗?
- 如果是这样,是否有办法覆盖此行为并捕获其中包含的任何异常
ConstraintViolationException
? - 如果没有,有什么好的解决方法?
想法?
谢谢。