How to catch and wrap exceptions thrown by JTA when a container-managed-tx EJB commits?

后端 未结 4 1019
别那么骄傲
别那么骄傲 2020-12-13 05:04

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 trans

相关标签:
4条回答
  • 2020-12-13 05:31

    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...

    0 讨论(0)
  • 2020-12-13 05:32

    There's a caveat to what I said about REQUIRES_NEW and BMT in the original question.

    See the EJB 3.1 spec, section 13.6.1Bean-Managed Transaction Demarcation, in Container responsibilities. It reads:

    The container must manage client invocations to an enterprise bean instance with bean-managed transaction demarcation as follows. When a client invokes a business method via one of the enterprise bean’s client views, the container suspends any transaction that may be associated with the client request. If there is a transaction associated with the instance (this would happen if a stateful session bean instance started the transaction in some previous business method), the container associates the method execution with this transaction. If there are interceptor methods associated with the bean instances, these actions are taken before the interceptor methods are invoked.

    (italics mine). That's important, because it means that a BMT EJB doesn't inherit the JTA tx of a caller that has an associated container managed tx. Any current tx is suspended, so if a BMT EJB creates a tx it is a new transaction, and when it commits it commits only its transaction.

    That means you can use a BMT EJB method that begins and commits a transaction as if it were effectively REQUIRES_NEW and do something like this:

    @Stateless
    @TransactionManagement(TransactionManagementType.BEAN)
    class TheEJB {
    
        @Inject private EntityManager em;
    
        @Resource private UserTransaction tx; 
    
        // Note: Any current container managed tx gets suspended at the entry
        // point to this method; it's effectively `REQUIRES_NEW`.
        // 
        public methodOfInterest() throws AppValidationException, SomeOtherAppException {
           try {
               tx.begin();
               // For demonstration's sake create a situation that'll cause validation to
               // fail at commit-time here, like
               someEntity.getCollectionWithMinSize1().removeAll();
               em.merge(someEntity);
               tx.commit();
           } catch (ValidationException ex) {
               throw new AppValidationException(ex);
           } catch (PersistenceException ex) {
               // Go grubbing in the exception for useful nested exceptions
               if (isConstraintViolation(ex)) {
                   throw new AppValidationException(ex);
               } else {
                   throw new SomeOtherAppException(ex);
               }
           }
        }
    
    }
    

    This puts the commit under my control. Where I don't need a transaction to span several calls across multiple different EJBs this allows me to handle all errors, including errors at commit time, within my code.

    The Java EE 6 tutorial page on bean managed transactions doesn't mention this, or anything else about how BMTs are called.

    The talk about BMT not being able to simulate REQUIRES_NEW in the blogs I linked to is valid, just unclear. If you have a bean-managed transactional EJB you cannot suspend a transaction that you begun in order to begin another. A call to a separate helper EJB may suspend your tx and give you the equivalent of REQUIRES_NEW but I haven't tested yet.


    The other half of the problem - cases where I need container managed transactions because I have work that must be done across several different EJBs and EJB methods - is solved by defensive coding.

    Early eager flushing of the entity manager allows me to catch any validation errors that my JSR330 validation rules can find, so I just need to make sure they're complete and comprehensive so I never get any check constraint or integrity violation errors from the DB at commit time. I can't handle them cleanly so I need to really defensively avoid them.

    Part of that defensive coding is:

    • Heavy use of javax.validation annotations on entity fields, and use of @AssertTrue validation methods where that isn't enough.
    • Validation constraints on collections, which I was delighted to see are supported. For example, I have an entity A with a collection of B. A must have at least one B, so I added a @Size(min=1) constraint to the collection of B where it's defined in A.
    • Custom JSR330 validators. I've added several custom validators for things like Australian Business Numbers (ABNs) to make sure I never try to send an invalid one to the database and trigger a DB-level validation error.
    • Early flushing of the entity manager with EntityManager.flush(). This forces validation to take place when it's under the control of your code, not later when JTA goes to commit the transaction.
    • Entity-specific defensive code and logic in my EJB facade to make sure that situations that cannot be detected by JSR330 validation do not arise and cause commit to fail.
    • Where practical, using REQUIRES_NEW methods to force early commit and allow me to handle failures within my EJBs, retry appropriately, etc. This sometimes requires a helper EJB to get around issues with self-calls to business methods.

    I still can't gracefully handle and retry serialization failures or deadlocks like I could when I was using JDBC directly with Swing, so all this "help" from the container has put me a few steps backwards in some areas. It saves a huge amount of fiddly code and logic in other places, though.

    Where those errors occur I've added a UI-framework level exception filter. It sees the EJBException wrapping the JTA RollbackException wrapping the PersistenceException wrapping the EclipseLink-specific exception wrapping the PSQLException, examines the SQLState, and makes decisions based on that. It's absurdly roundabout, but it works

    0 讨论(0)
  • 2020-12-13 05:44

    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.

    0 讨论(0)
  • 2020-12-13 05:47

    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.

    0 讨论(0)
提交回复
热议问题