如何处理GORM异常 [英] How to handle GORM exceptions
问题描述
我试图为Hibernate抛出的Optimistic锁类型异常实现异常处理,但遇到一个奇怪的问题。看来我无法抓住任何Gorm例外。
I'm trying to implement exception handling for Optimistic lock type exceptions that are thrown by Hibernate but I've encountered a strange issue. It seems I'm unable to catch any Gorm exceptions.
例如我在我的服务中有这个代码:
For example I have this code in my service:
try {
User user = User.get(1);
Thread.sleep(10000);
user.viewedAt(new Date());
user.save(flush:true);
} catch (OptimisticLockingException ex) {
log.error("Optimistic lock exception");
} catch (StaleObjectStateException ex) {
log.error("Optimistic lock exception");
}
当我用两个线程打这个块时,它会爆炸,异常传播到Grails的标准异常处理程序。即使报告的异常是 StaleObjectStateException
。
When I hit this block with two threads, it blows up and the exception propagates to Grails' standard exception handler. The catch blocks are never invoked even though the reported exception is StaleObjectStateException
.
我注意到我 >可以捕获异常,如果我让它传播到控制器并抓住它,但似乎我不能实现异常处理的服务是奇怪的。
I've noticed that I can catch the exception if I let it propagate to the controller and catch it there, but it seems I can't implement exception handling in the service which is weird.
我缺少什么?
推荐答案
我已经到底了,我发布它,以防万一否则会进入这个。发生此问题是因为try / catch块处于事务服务中。虽然grails报告说在 save()
调用期间抛出了异常,但实际上它被称为 整个方法,当交易提交时。
I got to the bottom of this and I'm posting it in case anyone else runs into this. The issue occurred because the try/catch block was in a transactional service. Although grails reported that the exception was thrown during the save()
call, in reality it was called AFTER the entire method, when the transaction was committed.
所以似乎:
-
flush:true
对事务性服务没有影响 - 在事务性服务中无法捕获GORM相关的异常,至少没有一些工作
flush: true
has no effect on transactional services- It's not possible to catch GORM related exceptions in transactional services, at least not without some work
我终于通过手动管理自己的交易来解决这个问题,比如
I finally worked around this by manually managing the transaction myself i.e.
try {
User.withNewTransaction {
User user = User.get(id); // Must reload object
.. // do stuff
user.save(flush:true)
}
} catch (OptimisticLockingException ex) {
...
}
我希望这对别人有用!
这篇关于如何处理GORM异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!