Django的文档介绍了transaction.atomic()和例外情况:
https://docs.djangoproject.com/en/1.10/topics/db/transactions/#django.db.transaction.atomic
避免捕捉原子内部的异常! 当退出一个原子块时,Django会查看它是正常退出还是异常退出,以确定是提交还是回滚。如果捕获并处理原子块中的异常,则可以向Django隐藏问题已经发生的事实。这可能导致意外的行为。 这主要是DatabaseError及其子类(如IntegrityError )所关心的问题。在发生这样的错误后,事务就被破坏了,Django将在原子块的末尾执行回滚。如果您试图在回滚之前运行数据库查询,Django将引发一个TransactionManagementError。当与ORM相关的信号处理程序引发异常时,也可能会遇到此行为。 捕获数据库错误的正确方法是围绕一个原子块,如上面所示。如果有必要,为此添加一个额外的原子块。此模式还有另一个优点:它显式地分隔了当异常发生时哪些操作将被回滚。 如果捕获原始SQL查询引发的异常,Django的行为是未指定的,并且依赖于数据库。
这样做可以吗,还是会导致“意想不到的行为”?
with transaction.atomic():
# something
try:
# something
except:
logger.exception("Report error here.")
raise发布于 2017-03-03 20:38:14
基于文档,我将确保重新引发正确的异常,其他您可能独立处理的错误。对于django,只需要通知它在与数据库对话时出错的事情。
with transaction.atomic():
# something
try:
# something
except DatabaseError as db_err:
logger.exception("Report error here.")
raise db_err
except Exception:
# do something else
# no need to reraise
# as long as you handle it properly and db integrity is guaranteed发布于 2018-03-22 16:04:42
这样做可以吗,还是会导致“意想不到的行为”?
with transaction.atomic():
# something
try:
# something
except:
logger.exception("Report error here.")
raise除了bare what子句(您至少需要except Exception:)之外,这是可以的,前提是您的记录器没有接触数据库(这无论如何都是一个非常糟糕的主意),并且记录器调用不会引发另一个异常(在这种情况下,我不知道实际会发生什么)。
但是,transaction.atomic()块和try/except也会得到相同的结果,即:
try:
with transaction.atomic():
# something
# something
except Exception:
logger.exception("Report error here.")
raise发布于 2021-12-09 07:19:10
这个例子可以消除你的疑虑。
with transaction.atomic():
try:
# if you do something that raises ONLY db error. ie. Integrity error
except Exception:
# and you catch that integrity error or any DB error like this here.
# now if you try to update your DB
model = Model.objects.get(id=1)
model.description = "new description"
model.save()
# This will be illegal to do and Django in this case
# will raise TransactionManagementError suggesting
# you cannot execute any queries until the end of atomic block.现在,如果您正在引发这样的自定义异常:
with transaction.atomic():
try:
# raising custom exception
raise Exception("some custom exception")
except Exception:
# and you catch that exception here
# now if you try to update your DB
model = Model.objects.get(id=1)
model.description = "new description"
model.save()
# Django will allow you to update the DB.https://stackoverflow.com/questions/42586841
复制相似问题