gpt4 book ai didi

java - CMT 无状态 bean 中的异常处理

转载 作者:行者123 更新时间:2023-12-01 04:28:22 31 4
gpt4 key购买 nike

是否可以捕获 CMT(容器管理事务)无状态 bean 中的异常?

当我尝试时,下面的代码不会捕获任何异常。如果我使用BMT(Bean Managed Transaction),我可以捕获异常。但我想留在 CMT。

@Path("books")
public class BookResource
{

@EJB
private BooksFacade book_facade;

private Books local_book;


@POST
@Consumes({"application/xml", "application/json"})
public Response create(Books entity)
{
try
{
book_facade.create(entity);
} catch (RuntimeException ex)
{
System.out.println("Caught database exception");
}
return Response.status(Response.Status.CREATED).build();
}



public class TXCatcher
{

//@Resource
//UserTransaction tx;
private final static Logger LOG = Logger.getLogger(TXCatcher.class.getName());

@AroundInvoke
public Object beginAndCommit(InvocationContext ic) throws Exception
{
//ic.proceed();
System.out.println("Invoking method: " + ic.getMethod());
try
{
//tx.begin();
Object retVal = ic.proceed();
//tx.commit();
return retVal;
}catch (RollbackException e)
{
LOG.log(Level.SEVERE, "-----------------Caught roolback(in interceptor): {0}", e.getCause());
System.out.println("Invoking method: " + ic.getMethod());
throw new CustomEx("Database error");
}catch (RuntimeException e)
{
LOG.log(Level.SEVERE, "-----------------Caught runtime (in interceptor): {0}", e.getCause());
System.out.println("Invoking method: " + ic.getMethod());
//tx.rollback();

throw new CustomEx("Database error",e.getCause());
//throw new CustomEx("Database error");
}



//return ic.proceed();


}

}

最佳答案

这取决于您想要捕获什么类型的问题。您可以尝试显式 EntiyManager.flush,但根据您的数据源隔离级别,某些错误在事务提交之前无法捕获,并且 CMT 没有捕获事务提交错误的机制。如果是这种情况,您唯一的选择就是使用 BMT(即使您说您不想这样做)。唯一可能使其更容易接受的建议是编写一个行为与 CMT 类似的 EJB 拦截器(即,将 UserTransaction 注入(inject)拦截器,并在 @AroundInvoke 中开始/提交/回滚)。

关于java - CMT 无状态 bean 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18242479/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com