0

I would like to catch 500 exception and return a http 4XX exception instead. Using "except Exception" will catch all exceptions which is not desired. I was wondering is there a way to catch only 500 errors

try:
   <code>
except <Exception class>:
   return http 404 reponse

I searched a lot but couldn't figure out how to do the same. Thanks in advance

Gocht
  • 9,924
  • 3
  • 42
  • 81
Maverick
  • 484
  • 2
  • 9
  • 20
  • I think you need [middlewares](https://docs.djangoproject.com/en/1.8/topics/http/middleware/#process-exception) – Gocht Jun 19 '15 at 21:56
  • There is no 500 exception. The WSGI handler catches _any_ exception and returns a 500 response if there is one, save a few special cases such as `Http404` or `PermissionDenied`. – knbk Jun 19 '15 at 22:17
  • So should i use except Exception: ? Thats the only way ? @knbk – Maverick Jun 19 '15 at 22:33
  • Well, I'm not sure what it is you want exactly, so I can't comment on that. – knbk Jun 19 '15 at 22:42

1 Answers1

0

I'm not sure that returning 404 instead of 500 is a good idea, but you can acheive this by defining a custom error handler for 500 errors.

In your urls.py:

handler500 = 'mysite.views.my_custom_error_view'

In your views.py:

from django.http import HttpResponse

def my_custom_error_view(request):
    """
    Return a 404 response instead of 500.
    """
    return HttpResponse("error message", status_code=404)
Alasdair
  • 298,606
  • 55
  • 578
  • 516