2
votes

I have a EJB using CMT. This EJB is a JSON JERSEY REST web service. This web service is called by a standalone GSON REST client.
This EJB calls below classes in a single transation in below sequence : 1) A DB DAO class which does a DB insert operation. 2) LDAP client class which inserts the user in Active Directory.

When any exception occurs the EJB/web service throws a 500 internal server error and container rollsback the transaction. I want to capture this error, convert to meaningful message and send to the consumer as part of my response Object. How can I catch this EJB rollback exception ? I found that if I catch it inside the EJB then the transaction does not get rollback. Are there any interceptors which will intercept the EJB rollback exception and catch it ?

Below is my EJB code :

@Interceptors(SpringBeanAutowiringInterceptor.class)
@Stateless(name = "RegistrationServiceImpl", mappedName = "EJB-model-RegistrationServiceImpl")
@Path("registration")
public class RegistrationServiceImpl implements IRegistrationService {
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public RegistrationResponse validateMemberRegInfo(RegistrationRequest request){
        // CALL DB DAO throws DB exception
        // CALL LDAP client throws LDAP exception
    }
}
1

1 Answers

1
votes

You cannot catch transaction commit failures from within a container-managed transaction method because the transaction commit won't happen until the method ends. You'll either need to catch the exception in the caller (e.g., the servlet), or you'll need to use bean-managed transactions. For example:

@TransactionManagement(BEAN)
public class RegistrationServiceImpl implements IRegistrationService {
    @Resource UserTransaction userTran;
    public RegistrationResponse validateMemberRegInfo(RegistrationRequest request){
        try {
            userTran.begin();
            // CALL DB DAO throws DB exception
            // CALL LDAP client throws LDAP exception
            userTran.commit();
        } catch (...) {
            ...
        } catch (TransactionRolledbackException e) {
            ...
        }
    }
}