Reputation: 1027
Let we have the code:
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
The problem is when I re-raise the exception, my 'SOME DATA' will be lost too, because it's made within same transaction. Is there a context or something to execute code within SEPARATE transaction/connection?
There is a point, that the code has bad architect. In a normal flow there should not be a neccessity to save_some_data...
As proposed solution they said:
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
But dirty code gets once more dirty.
I'd prefer if it was something like:
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
Any ideas are welcome!
Upvotes: 3
Views: 174
Reputation: 7923
I don't see any reason to use separate connections. Isn't it enough just to use a lower level 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)
Upvotes: 1