0

I have this middelware which is suppose to catch 500/400 exceptions and deal with them. But it never gets called. I've put it in the beginning and end of the MIDDLEWARE_CLASSES but it still doesn't run when an exception is raised:

vertical/middleware.py:

class HandleExceptionsMiddleware(object):
       def process_exception(self, request, exception):
             print >> sys.stderr, "exception has been raised"
             # Get the exception info now, in case another exception is thrown later.
             if isinstance(exception, http.Http404):
                   return self.handle_404(request, exception)
             else:
                   return self.handle_500(request, exception)

settings.py

MIDDLEWARE_CLASSES = (
       'vertical.middleware.HandleExceptionsMiddleware',
       'django.contrib.sessions.middleware.SessionMiddleware',
       'django.middleware.common.CommonMiddleware',
       'debug_toolbar.middleware.DebugToolbarMiddleware',
       'django.middleware.csrf.CsrfViewMiddleware',
       'django.contrib.auth.middleware.AuthenticationMiddleware',
       'django.contrib.messages.middleware.MessageMiddleware',
       'django.middleware.clickjacking.XFrameOptionsMiddleware',
 )
S. Developer
  • 156
  • 2
  • 6
  • Two quick questions: If you would add an __init__() method, is that invoked? And: can you do a "from vertical.middleware import HandleExceptionsMiddleWare" from your (manage.py) shell? – Freek Wiekmeijer Apr 18 '14 at 06:05
  • 1
    This question is answered in http://stackoverflow.com/questions/6466792/for-a-django-middleware-class-how-can-process-request-work-just-fine-but-proce – omar Apr 18 '15 at 11:43

2 Answers2

0

middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.

Leonardo.Z
  • 9,425
  • 3
  • 35
  • 38
  • 2
    I have the same issue. The question mentions - I've put it in the beginning and end of the MIDDLEWARE_CLASSES but it still doesn't run. – ksrini Nov 24 '14 at 15:48
0

Following checklist helped me with similar problem:

  1. Check if middleware is properly created (refer to middleware docs)
  2. Check python dotted path in MIDDLEWARES with middleware you are working on
  3. Check if your middleware is at the bottom of MIDDLEWARES

If still not working, that means other middleware captures exception and returns response, or other middleware is calling your view out of order or way too soon.

  1. Check if your other middlewares are returning None (explicitly or implicitly)
  2. Check if your other middlewares are not directly calling view_func in process_view
proxy
  • 469
  • 5
  • 12