捕获EJB回滚异常

时间:2012-10-22 20:28:36

标签: ejb-3.1

我有一个使用CMT的EJB。此EJB是JSON JERSEY REST Web服务。这个网络服务是 由独立的GSON REST客户端调用 此EJB在以下序列的单个转换中调用以下类: 1)DB DAO类,它执行DB插入操作。 2)在Active Directory中插入用户的LDAP客户端类。

发生任何异常时,EJB / Web服务会抛出500内部服务器错误 和容器回滚事务。 我想捕获此错误,转换为有意义的消息并作为我的响应对象的一部分发送给使用者。 如何捕获此EJB回滚异常?我发现如果我在EJB中捕获它,那么事务就不会回滚。是否有任何拦截器会拦截EJB回滚异常并捕获它?

以下是我的EJB代码:

@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 个答案:

答案 0 :(得分:1)

您无法从容器管理的事务方法中捕获事务提交失败,因为在方法结束之前不会发生事务提交。您需要在调用者中捕获异常(例如,servlet),或者您需要使用bean管理的事务。例如:

@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) {
            ...
        }
    }
}
相关问题