Re-raising exceptions in django with atomic()

Hey,

Let’s consider the following.


with transaction.atomic():
   do_db_stuff()
   except SomeError as ex:
      some_action_on_error()
      raise ex

So basically, within an atomic block, in case some exception is raised, I want to perform an action. But I also want to ensure that the transaction.atomic() works as expected (considering that this block may or not be within a larger transaction.atomic() as well). Ideally also preserve the exception stack trace to make futur-me life easier.

The above is what I could come up with. Any gotchas I’m missing? Or better alternatives to achieve these goals?

This specific code lives within Django’s signals receiver, if that matters.

Yes your plan is fine. But syntacticaally you probably want:

with transaction.atomic():
    try:
        do_db_stuff()
    except SomeError:
        some_action_on_error()
        raise

Note you can use bare raise inside an except block to reraise the same exception.