23

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?

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

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:

  • 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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.