I have a datamigration I actually want to roll back if certain condition happen.
I know that migrations are automatically enclosed in a transaction, so I am safe just raising an exception, and then trust all changes to be rolled back. But which exception should I raise to abort my Django data migration?
Should I write my own exception, or am I fine with raise Exception('My message explaining the problem')
?
What is best practice?
The right way is raising a CommandError('My message explaining the problem')
(package django.core.management
).
Migrations are executed within a command, and the difference is: if you use any other exception class, the result will be the same, but the traceback is going to be displayed in the user's terminal, making the error to look something wrong about the code, but you did raise the exception on purpose, wanting to (1) stop the code (2) rollback any change and (3) let the user know why, but there is no reason to show the traceback, so using CommandError
the error is going to be shown without traceback trail, like the following, right before abort the command:
CommandError: My message explaining the problem