2

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.

user193130
  • 8,009
  • 4
  • 36
  • 64
  • There is already one for `403`: https://docs.djangoproject.com/en/1.8/topics/http/urls/#error-handling – karthikr Jun 25 '15 at 15:54
  • @karthikr Unfortunately, I already came across that and it seems like that's what the `settings.handler*` refers to. The problem is that the exception instance is [not being passed into the view as an argument](https://docs.djangoproject.com/en/1.8/ref/views/#http-forbidden-view). My question is whether there's a way to retrieve that exception instance, perhaps unconventionally via introspection? – user193130 Jun 25 '15 at 15:58

1 Answers1

1

This feature has been implemented as ticket 24733.

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

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Frankly kind of shocked that this simple use case had not been implemented until now but I'm glad it finally landed :) – user193130 Jul 07 '15 at 22:17