I'm struggling with a problem with an EJB3 class that manages a non-trivial data model. I have constraint validation exceptions being thrown when my container-managed transactional methods commit. I want to prevent them from being wrapped in EJBException
, instead throwing a sane application exception that callers can handle.
To wrap it in a suitable application exception, I must be able to catch it. Most of the time a simple try/catch does the job because the validation exception is thrown from an EntityManager
call I've made.
Unfortunately, some constraints are only checked at commit time. For example, violation of @Size(min=1)
on a mapped collection is only caught when the container managed transaction commits, once it leaves my control at the end of my transactional method. I can't catch the exception thrown when validation fails and wrap it, so the container wraps it in a javax.transaction.RollbackException
and wraps that in a cursed EJBException
. The caller has to catch all EJBException
s and go diving in the cause chain to try to find out if it's a validation issue, which is really not nice.
I'm working with container managed transactions, so my EJB looks like this:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER
class TheEJB {
@Inject private EntityManager em;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public methodOfInterest() throws AppValidationException {
try {
// For demonstration's sake create a situation that'll cause validation to
// fail at commit-time here, like
someEntity.getCollectionWithMinSize1().removeAll();
em.merge(someEntity);
} catch (ValidationException ex) {
// Won't catch violations of @Size on collections or other
// commit-time only validation exceptions
throw new AppValidationException(ex);
}
}
}
... where AppValidationException
is a checked exception or an unchecked exception annotated @ApplicationException
so it doesn't get wrapped by EJB3.
Sometimes I can trigger an early constraint violation with an EntityManager.flush()
and catch that, but not always. Even then, I'd really like to be able to trap database-level constraint violations thrown by deferred constraint checks at commit time too, and those will only ever arise when JTA commits.
Help?
Already tried:
Bean managed transactions would solve my problem by allowing me to trigger the commit within code I control. Unfortunately they aren't an option because bean managed transactions don't offer any equivalent of TransactionAttributeType.REQUIRES_NEW
- there's no way to suspend a transaction using BMT. One of the annoying oversights of JTA.
See:
... but see answers for caveats and details.
javax.validation.ValidationException
is a JDK exception; I can't modify it to add an @ApplicationException
annotation to prevent wrapping. I can't subclass it to add the annotation; it's thrown by EclpiseLink, not my code. I'm not sure that marking it @ApplicationException
would stop Arjuna (AS7's JTA impl) wrapping it in a RollbackException
anyway.
I tried to use a EJB3 interceptor like this:
@AroundInvoke
protected Object exceptionFilter(InvocationContext ctx) throws Exception {
try {
return ctx.proceed();
} catch (ValidationException ex) {
throw new SomeAppException(ex);
}
}
... but it appears that interceptors fire inside JTA (which is sensible and usually desirable) so the exception I want to catch hasn't been thrown yet.
I guess what I want is to be able to define an exception filter that's applied after JTA does its thing. Any ideas?
I'm working with JBoss AS 7.1.1.Final and EclipseLink 2.4.0. EclipseLink is installed as a JBoss module as per these instructions, but that doesn't matter much for the issue at hand.
UPDATE: After more thought on this issue, I've realised that in addition to JSR330 validation exceptions, I really also need to be able to trap SQLIntegrityConstraintViolationException from the DB and deadlock or serialization failure rollbacks with SQLSTATE 40P01 and 40001 respectively. That's why an approach that just tries to make sure commit will never throw won't work well. Checked application exceptions can't be thrown through a JTA commit because the JTA interfaces naturally don't declare them, but unchecked @ApplicationException
annotated exceptions should be able to be.
It seems that anywhere I can usefully catch an application exception I can also - albeit less prettily - catch an EJBException and delve inside it for the JTA exception and the underlying validation or JDBC exception, then do decision making based on that. Without an exception filter feature in JTA I'll probably have to.
Setting eclipselink.exception-handler
property to point to an implementation of ExceptionHandler
looked promising, but didn't work out.
The JavaDoc for ExceptionHandler
is ... bad ... so you'll want to look at the test implementation and the tests (1, 2) that use it. There's somewhat more useful documentation here.
It seems difficult to use the exception filter to handle a few specific cases while leaving everything else unaffected. I wanted to trap PSQLException
, check for SQLSTATE 23514 (CHECK
constraint violation), throw a useful exception for that and otherwise not change anything. That doesn't look practical.
In the end I've dropped the idea and gone for bean managed transactions where possible (now that I properly understand how they work) and a defensive approach to prevent unwanted exceptions when using JTA container managed transactions.
I haven't tried this. But I am guessing this should work.
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
class TheEJB {
@Inject
private TheEJB self;
@Inject private EntityManager em;
public methodOfInterest() throws AppValidationException {
try {
self.methodOfInterestImpl();
} catch (ValidationException ex) {
throw new AppValidationException(ex);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public methodOfInterestImpl() throws AppValidationException {
someEntity.getCollectionWithMinSize1().removeAll();
em.merge(someEntity);
}
}
The container is expected to start a new transaction and commit within the methodOfInterest
, therefore you should be able to catch the exception in the wrapper method.
Ps: The answer is updated based on the elegant idea provided by @LairdNelson...
javax.validation.ValidationException is a JDK exception; I can't modify it to add an @ApplicationException annotation to prevent wrapping
In addition to your answer: you can use the XML descriptor to annotate 3rd party classes as ApplicationException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With