I'm writing a REST application using WildFly 8 (JAX-RS 2.0, EJB 3.2 and JPA 2.1).
I have a JAX-RS resource which is also an EJB (stateless session bean with implicit container-managed transactions):
@Path("myresources")
@Stateless
public class MyResource {
@PersistenceContext(name = "MyDataSource")
private EntityManager em;
@POST
public Response create() {
MyEntity invalidBean = new MyEntity();
em.persit(invalidBean);
...
}
}
MyEntity
is decorated with bean validation annotations:
@Entity
public class MyEntity {
@NotNull
private String field;
...
}
Finally, I have defined an ExceptionMapper
for ConstraintViolationException
:
@Provider
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException exception) {
...
}
}
When MyResource.create
is called, I expect the following behavior:
- The invalid bean is saved using JPA
- The end of my service implementation is reached without any exception
- A commit is triggered by the container (container-managed transaction)
- JTA launches bean validation to check constraints on the saved bean
- A
ConstraintViolationException
is thrown - JAX-RS dispatches it to my
ConstraintViolationExceptionMapper
However, this does not work properly: the ConstraintViolationException
is actually thrown, but deeply wrapped inside an EJBTransactionRolledbackException
. So, my ExceptionMapper
does not catch it.
I already configured ConstraintViolationException
to be an ApplicationException
(following this guide). Thus, I'm now able to catch ConstraintViolationException
when thrown from my own code, but still not when thrown by JTA.
This thread seems related, but I would prefer to avoid:
- explicit transaction handling
- vendor-specific solutions
Any idea to solve this problem?
Thanks!