我们有代码:
def some_function():
with transaction.atomic():
# some code which writes to DB
try:
call_method_which_may_raise_exception()
except KnownException as e:
save_some_data_about_exception_to_database(e)
raise
# other code which writes to DB
问题是当我重新引发异常时,我的“某些数据”也会丢失,因为它是在同一个事务中完成的。 是否有在SEPARATE事务/连接中执行代码的上下文或其他内容?
有一点,代码有糟糕的架构师。在正常流程中,save_some_data ...
不应该是必要的根据提议的解决方案,他们说:
def some_function():
exception_to_save = None
try:
with transaction.atomic():
# some code which writes to DB
try:
call_method_which_may_raise_exception()
except KnownException as e:
exception_to_save = e
raise
# other code which writes to DB
except Exception as e:
if exception_to_save:
save_some_data_about_exception_to_database(exception_to_save)
raise
但是脏代码再次变脏了。
我更喜欢它是否像:
def some_function():
with transaction.atomic():
# some code which writes to DB
try:
call_method_which_may_raise_exception()
except KnownException as e:
with transaction.separate_connection():
save_some_data_about_exception_to_database(e)
raise
# other code which writes to DB
欢迎任何想法!
答案 0 :(得分:1)
我认为没有任何理由使用单独的连接。仅仅使用较低级别的API还不够吗?
def some_function():
transaction.set_autocommit(False)
try:
call_method_which_may_raise_exception()
except KnownException as e:
transaction.rollback()
save_some_data_about_exception_to_database(e)
raise
finally:
transaction.commit()
transaction.set_autocommit(True)