显然,我们无法直接捕获 OptimisticLockException(在 javax.persistence 或 org.eclipse.persistence.exceptions 包中),因为它被包装在其他异常中。
我测试了这段代码:
try{
account.someFunction();
}catch(OptimisticLockException o1){
logger.log(Level.DEBUG, "org.eclipse.persistence.exceptions.OptimisticLockException thrown !");
}catch(javax.persistence.OptimisticLockException o2){
logger.log(Level.DEBUG, "javax.persistence.OptimisticLockException thorwn !");
}catch(Exception e){
int i=1;
for(Throwable t=(Throwable)e; t!=null; t=t.getCause()){
if(t instanceof OptimisticLockException)
logger.log(Level.DEBUG, "org.eclipse.persistence.exceptions.OptimisticLockException thrown by Exception block ! " + i);
else if(t instanceof javax.persistence.OptimisticLockException)
logger.log(Level.DEBUG, "javax.persistence.OptimisticLockException thrown by Exception block ! " + i);
else
logger.log(Level.DEBUG, t + " " + i);
i++;
}
}
我得到:
2012-11-26 14:58:03,515 致命 [com.sim.web.LoginBean] javax.ejb.EJBException:事务中止 1
2012-11-26 14:58:03,515 致命 [com.sim.web.LoginBean] javax.transaction.RollbackException:标记为回滚的事务。2
2012-11-26 14:58:03,515 FATAL [com.sim.web.LoginBean] javax.persistence.OptimisticLockException 抛出异常块!3
2012-11-26 14:58:03,515 FATAL [com.sim.web.LoginBean] org.eclipse.persistence.exceptions.OptimisticLockException 抛出异常块!4
所以首先有一个org.eclipse.persistence.exceptions.OptimisticLockException
被包裹进javax.persistence.OptimisticLockException
哪个被包裹进javax.transaction.RollbackException
哪个被包裹进javax.ejb.EJBException
(我正在使用EJB和JTA)。
我无法使用 catch 块RollbackException
异常进行测试,因为 Eclipse 没有检测到可以抛出这样的异常:Unreachable catch block for RollbackException. This exception is never thrown from the try statement body
。
这很丑陋,但我认为我注定要捕获类型异常Exception
并递归测试它是否包含类型异常OptimisticLockException
...
感谢您之前的建议