BlueMagma
BlueMagma

Reputation: 2515

handlers for specific Exception

I have created a specific Exception class

class myException(Exception):
    ...

and I raise the exception on some specific view

In django already exist a way to handle some exception (like Http404, Http403....) in urls.py

handler404 = 'myViews.error.not_found'

What I'd like to do is to handle myException, in order to redirect to another view.

How can I do that ?

Upvotes: 1

Views: 57

Answers (1)

James Henstridge
James Henstridge

Reputation: 43949

You should be able to achieve this by writing and registering a custom Django middleware class for your project.

In the middleware's process_exception method, check for the exception you are interested in and generate an appropriate HttpResponse:

def process_exception(self, request, exception):
    if isinstance(exception, myException):
        return http.HttpResponse("myException raised")
    else:
        # Perform standard error handling for other exceptions:
        return None

Upvotes: 2

Related Questions