简体   繁体   English

try/except 块是否会导致 commit_on_success 失败

[英]Does try/except block causes commit_on_success to fail

@transection.commit_on_success
def recordIt(...)
   try:
       ....
       recordable = firstDataInsertionFunction(...)
       if recordable:
          myRec = SecondDataInsertion(.....)

    except:
       ....

As for commit_on_success , if my second data insertion fails, django must automatically rollback, so my first data insertion will be rolled back too...至于commit_on_success ,如果我的第二次数据插入失败,django 必须自动回滚,所以我的第一次数据插入也会回滚......

But this is not working, and first inserted data is saved to db, while i could not see the result of second insertion on my database... Is try/except causes commit_on_success to fail?但这不起作用,第一次插入的数据被保存到数据库中,而我在我的数据库上看不到第二次插入的结果...... try/except 会导致 commit_on_success 失败吗? Because as documentation says:因为正如文档所说:

If the function returns successfully, then Django will commit all work done within the function at that point.如果 function 成功返回,则 Django 将提交 function 内完成的所有工作。 If the function raises an exception, though, Django will roll back the transaction.但是,如果 function 引发异常,Django 将回滚事务。

And try handles all exceptions.并尝试处理所有异常。 Is is the problem of my not working commit_on_success ?是我不工作的问题commit_on_success吗?

First of all, don't ever do except: .首先,永远不要做except: It's just bad, and catches too much, and hides bugs.这很糟糕,并且捕获了太多,并且隐藏了错误。

And yes, if you handle the exception, then commit_on_success cannot possibly know there was an error.是的,如果您处理异常,则commit_on_success不可能知道有错误。 If you need to run logic on exception, reraise it afterwards (just raise , with no argument).如果您需要在异常上运行逻辑,请在之后重新引发它(只需raise ,不带参数)。 Or rollback yourself.或者自己回滚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM