Django: How to get exception instance in error handlers

1.6k views Asked by At

Django has built-in default views which are used automatically when exceptions such as PermissionDenied, Http404, SuspiciousOperation, etc. are raised. This is a convenient feature of Django which I love, but it seems to have a limitation.

I am raising an exception with a message: raise PermissionDenied('You are not an xyz and have no access to foobar')

Is there a context variable containing the original exception instance available in the templates (i.e. 403.html) called by the original error handlers so that I can access the message?

If not, is it possible to get a hold of the original exception with a custom handler (settings.handler403, etc.) so I can inject it into the context?


NOTE: I believe I can create a custom middleware with process_exception, but I would like to avoid this if possible since my guess is I would be duplicating a lot of existing Django logic and it's cleaner to reuse it. Also, it looks like a custom process_exception would override the logging in django.core.handlers.base amongst other behaviors. Re-implementing all that just for the sake of injecting exception info into an error template seemed kind of silly.

1

There are 1 answers

1
Alasdair On BEST ANSWER

This feature has been implemented as ticket 24733.

In Django 1.9 and later, the exception will be passed to the error handlers.