Catching errors inside transaction.atomic()

581 views
Skip to first unread message

Alex Krupp

unread,
Jun 13, 2017, 10:52:28 AM6/13/17
to Django users
The Django documentation gives a warning to avoid catching errors inside transaction.atomic() blocks, and to use nested transactions if you need to do so. But in the case where we have code like:

with transaction.atomic():
   
# Create and save some models here

   
try:
       
SomeModel.objects.get(id=NON_EXISTENT_ID)
   
except SomeModel.DoesNotExist:
       
raise SomeCustomError()

Will anything bad actually happen if we just immediately raise a custom error without doing any other error handling? The expected behavior in this case would be that the entire transaction gets rolled back, and so nothing before or after the exception is committed.

I'm just wondering in cases like these there is any reason for using the recommended nested transaction, or if it's just extra code that's not serving any purpose. The examples only speak to cases where there is there would otherwise be database queries getting executed in between the first database error and the end of the transaction, which isn't the case here.

Jani Tiainen

unread,
Jun 13, 2017, 11:25:57 AM6/13/17
to django...@googlegroups.com
Catching errors inside transaction might lead inconsistent state if the database if error handling swallows exception.

Reraising exception or like you want to do raise new exception it would work as expected.

Nested atomic blocks can be used to safely rollback state of database if you want to handle smaller units of transactiond.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8765cfc1-6083-4f6e-8f86-ace888a0ad21%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages