How to handle database exceptions in Django?

Question:

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"

  1. Is the the recommended way?

  2. Are there any good tutorials on error handling (i.e. blog posts) that you would recommend as a good approach?

Asked By: Prometheus

||

Answers:

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.

Answered By: arie

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:

  • Error
  • InterfaceError
  • DatabaseError
  • DataError
  • OperationalError
  • IntegrityError
  • InternalError
  • ProgrammingError
  • NotSupportedError

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")
Answered By: Kai – Kazuya Ito
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.