Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Framework : How to catch all occuring server errors centrally and trigger events on such errors

I am looking for the best possible solution where I can do the following :

  1. Catch every exception where ever it happens in the django applications
  2. Trigger various events like mailers , post to Analytics providers or log to the logger.
  3. Create a central error handler , that will take different actions on different conditions.

If there is a way to do this , how can it be done and how to go about it?

like image 845
Priyabrata Patnaik Avatar asked Mar 24 '26 09:03

Priyabrata Patnaik


2 Answers

Django has a an event logging functionality which uses Python logger to deliver all the tasks you're looking for. You can read more about it here

like image 131
zom-pro Avatar answered Mar 25 '26 22:03

zom-pro


While writing an app, you can use the following approach:

Whenever your app raises an Exception, use custom, app-specific exceptions like this

class FooException(Exception):
    """Base class for all app specific exceptions"""
    pass

classFooPermissionException(FooException):
    """Specific class for permission related exceptions"""
    pass

Now your app can provide a custom middleware

class FooExceptionMiddleware(object):
    """App specific middleware to handle app specific errors"""

    def process_exception(self, request, e):
        """Processes exceptions"""
        if isinstance(e, FooException):

            if isinstance(e, FooPermissionException):
                # handle PermissionExceptions here...

        return None

You can read more about Django middleware here.

Edit:

I think you can use the above approach, to catch all Exceptions: Have a look at Django's exception source code. Django's internal exceptions are siblings of Exception. So with something like the following code, you can possibly catch all exceptions, wherever they are raised in your project:

class AllExceptionMiddleware(object):
    def process_exception(self, request, e):
        if isinstance(e, Exception):
            # do stuff
        return None
like image 20
Mischback Avatar answered Mar 25 '26 23:03

Mischback