首页 > 解决方案 > EJB 拦截器。如果事务未提交,则捕获异常

问题描述

我有一个 EJB 拦截器,它应该捕获并处理事务中抛出的所有异常:

public class ExceptionsInterceptor {

@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    try {
        return invocationContext.proceed();
    } catch (Exception e) {
        throw new MyException(e);

    }
   }
}

但是,如果在休眠期间PesistenceException由于违反约束而引发刷新,我将无法捕获此异常。我知道在我的拦截器完成工作后休眠会刷新。但我需要捕获所有异常。

为了实现这一点,我用其他 EJB 装饰了这个 EJB。

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED_NEW)
public class TargetServiceBean implements TargetServiceLocal {

    @Override
    public boolean method1(Integer digit) {
        .. some code which my generate exception..
    }
}

@Stateless
@Interceptors(ExceptionsInterceptor.class)
public class TargetServiceBean implements TargetServiceDecorator {

    @Inject
    private TargetServiceLocal service;
    @Override
    public boolean method1(Integer digit) {
        service.method1(digit);
    }
}

它有效,但看起来像解决方法,我不喜欢这个解决方案。所以基本上我需要在事务之外运行拦截器。我怎样才能做到这一点?

标签: javajakarta-eeejbinterceptorejb-3.2

解决方案


推荐阅读