user423455 user423455 - 1 year ago 146
Python Question

Django - catch exception

It might be a Python newbie question...

#do something
raise Exception('XYZ has gone wrong...')

Even with DEBUG=True, I don't want this
raise Exception
gives me that yellow page. I actually want to handle the exception by redirecting users to an error page or shows the error (give a CSS error message on the top of the page...)

How do I handle that? Can someone guide me? If I simply raise it, I will get yellow debug page (again, I don't want certain exceptions to stop the site from functioning by showing the debug page when DEBUG=True).

How do I handle these exceptions in


Answer Source

You have three options here.

  1. Provide a 404 handler or 500 handler
  2. Catch the exception elsewhere in your code and do appropriate redirection
  3. 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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download