Django - catch exception
You have three options here.
- Provide a 404 handler or 500 handler
- Catch the exception elsewhere in your code and do appropriate redirection
- Provide custom middleware with the
process_exception
implemented
Middleware Example:
class MyExceptionMiddleware(object):
def process_exception(self, request, exception):
if not isinstance(exception, SomeExceptionType):
return None
return HttpResponse('some message')
You can raise a 404 error or simply redirect user onto your custom error page with error message
from django.http import Http404
#...
def your_view(request)
#...
try:
#... do something
except:
raise Http404
#or
return redirect('your-custom-error-view-name', error='error messsage')
- Django 404 error
- Django redirect
Another suggestion could be to use Django messaging framework to display flash messages, instead of an error page.
from django.contrib import messages
#...
def another_view(request):
#...
context = {'foo': 'bar'}
try:
#... some stuff here
except SomeException as e:
messages.add_message(request, messages.ERROR, e)
return render(request, 'appname/another_view.html', context)
And then in the view as in Django documentation:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}