python - 在 Django transaction.atomic() 中捕获并重新引发异常是否可以?

标签 python django transactions django-orm

Django 的文档是这样描述transaction.atomic() 和异常的:

https://docs.djangoproject.com/en/1.10/topics/db/transactions/#django.db.transaction.atomic

Avoid catching exceptions inside atomic!

When exiting an atomic block, Django looks at whether it’s exited normally or with an exception to determine whether to commit or roll back. If you catch and handle exceptions inside an atomic block, you may hide from Django the fact that a problem has happened. This can result in unexpected behavior.

This is mostly a concern for DatabaseError and its subclasses such as IntegrityError. After such an error, the transaction is broken and Django will perform a rollback at the end of the atomic block. If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError. You may also encounter this behavior when an ORM-related signal handler raises an exception.

The correct way to catch database errors is around an atomic block as shown above. If necessary, add an extra atomic block for this purpose. This pattern has another advantage: it delimits explicitly which operations will be rolled back if an exception occurs.

If you catch exceptions raised by raw SQL queries, Django’s behavior is unspecified and database-dependent.

这样做是否可以,或者这会导致“意外行为”吗?

with transaction.atomic():
    # something
    try:
        # something
    except:
        logger.exception("Report error here.")
        raise
    

最佳答案

根据文档,我会确保重新引发正确的异常,您可以独立处理其他错误。对于 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

关于python - 在 Django transaction.atomic() 中捕获并重新引发异常是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42586841/

相关文章:

python - 如何将 Pylint 与 Geany 集成,以便我可以将 Geany 用作 python IDE?

python - 如何离散化 pandas DataFrame 中的值并转换为二进制矩阵?

python - 是否有 Django "app"可以管理用户的个人资料?

javascript - 在 Azure 移动服务自定义 API 中使用事务

java - J2EE/JPA : Controlling Transaction Isolation

python - 在 Python 中预分配非常大的数组会导致 MemoryError

Python3 导入错误 : No module named '_tkinter'

django - 从 Django 表单序列化

html - 为什么 django 在使用 bootstrap 时在页面顶部显示 white lite

sql - 如何判断在 Oracle 事务中是否有未提交的工作?