Reputation: 33655
I want to known the best way to handle database exceptions and display messages back to the user. I have been looking at messages.add_message
in my views using a try.
For example:
The following error (1062, "Duplicate entry '123321' for key 'PRIMARY'")
. Display back to the user friendly message: "Error uploading CSV Duplicate entries"
Is the the recommended way?
Are there any good tutorials on error handling (i.e. blog posts) that you would recommend as a good approach?
Upvotes: 23
Views: 33005
Reputation: 1
In Django documentation, these exceptions below are introduced as database exceptions and in PEP 249, what causes these exceptions below are explained. For example, OperationalError is caused by lost update and write skew conditions, statement timeout, unexpected disconnection and so on:
In my opinion, using DatabaseError should be the easiest way to handle all database exceptions.
The below is the example of the view test
with DatabaseError:
# "views.py"
from .models import Person
from django.db import transaction, DatabaseError
from django.http import HttpResponse
@transaction.atomic
def test(request):
try:
obj = Person.objects.get(id=2)
obj.name = "David"
obj.save()
except DatabaseError as e:
return HttpResponse(e)
return HttpResponse("Success")
Upvotes: 1
Reputation: 18982
Database Exceptions
are documented,
check this answer to see an example of how to use them.
If you are encountering this error while processing a form you should probably handle the exception when validating your form. So in case an exception is raised you redisplay the form with the appropriate error message.
Upvotes: 17