我很难理解如何在Jboss Seam 2.2中正确捕获异常。
就计划Java而言,一个简单的try / catch就足够了,但是在Seam中,幕后发生的所有“魔法”(拦截器等),事情并没有按照我的预期发展。
以下是一个示例:我的页面调用了一个操作#{errorCaller.callError}
@Name("errorCaller")
public class ErrorCaller {
@In(create=true)
private ErrorClass errorClass;
@In
private Session hibernateReadWriteSession;
public void callError() {
System.out.println("MAKE AN ERROR!");
try {
errorClass.causeError();
} catch(Exception e) {
System.out.println("SAFELY CAUGHT!");
}
System.out.println("EVERYTHING IS OK, RIGHT?");
String hql = "from MyTable";
Query query = hibernateReadWriteSession.createQuery(hql);
query.list();
System.out.println("NOPE! THE TRANSACTION IS NOT ACTIVE!");
}
}
@Name("errorClass")
public class ErrorClass {
public void causeError() {
String nullString = null;
nullString.equals(null);
}
}
因此,如果这是计划旧的Java,那么异常将被处理,但是对于Seam,查询无法执行,因为事务处于非活动状态。
10:13:48,546 INFO [STDOUT] MAKE AN ERROR!
10:13:48,547 INFO [STDOUT] SAFELY CAUGHT!
10:13:48,547 INFO [STDOUT] EVERYTHING IS OK, RIGHT?
10:13:48,548 WARN [org.hibernate.util.JDBCExceptionReporter] SQL Error: 0, SQLState: null
10:13:48,548 ERROR [org.hibernate.util.JDBCExceptionReporter] Transaction is not active: tx=TransactionImple < ac, BasicAction: 0:ffff7f000101:126a:52986353:a6 status: ActionStatus.ABORT_ONLY >; - nested throwable: (javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: 0:ffff7f000101:126a:52986353:a6 status: ActionStatus.ABORT_ONLY >)
10:13:48,549 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] org.hibernate.exception.GenericJDBCException: Cannot open connection: javax.faces.el.EvaluationException: org.hibernate.exception.GenericJDBCException: Cannot open connection
如果我在errorClass.causeError()内部处理NullPointerException,Seam很乐意执行查询。
如何处理这样的情景?
我真的需要确保在方法本身内处理所有异常吗?
如果我需要在方法签名上自定义'抛出MySpecialException',该怎么办?
提前致谢! :)