We're having a problem on our django application. Occasionally, the database goes down/has too many connections, etc and Django continuously raises exceptions.
How can we catch these exceptions and redirect the user to an error page?
We're having a problem on our django application. Occasionally, the database goes down/has too many connections, etc and Django continuously raises exceptions.
How can we catch these exceptions and redirect the user to an error page?
If you want to show custom page for error 500 and then save the exceptions in logs, the following steps may help:
error_500.html
in your app templates/errors/
folder.Add view function error_500
to your app's views.py
:
def error_500(request): return render(request, 'errors/error_500.html')
Add routing to urls.py (either main or in your app's). For example
from django.conf.urls import handler404, handler500 from YOURAPP import views as yourapp_views
handler404 = yourapp_views.error_404 handler500 = yourapp_views.error_500
From now, in production mode (DEBUG=0, ALLOWED_HOSTS is set, run as WSGI etc.) , when exception occurs, Django should display contents of your error_500.html as Error 500 page. You will see more information in system logs.
With DatabaseError in test
view below, you will be able to handle all database exceptions then redirect users to error page when a database exception occurs:
# "views.py"
from django.db import transaction, DatabaseError
from django.shortcuts import redirect, render
from .models import Person
@transaction.atomic
def test(request):
try:
obj = Person.objects.get(id=2)
obj.name = "David"
obj.save()
except DatabaseError as e:
return redirect("/error-page/")
return render(request, 'myapp/success.html')
*In Django documentation, you can check database exceptions and in PEP 249, you can check what causes the database exceptions. For example, OperationalError is caused by unexpected disconnection, statement timeout, lost update and write skew conditions and so on.