user3628119
user3628119

Reputation: 357

Django - how to log error and display message

Currently, we use django logger to log errors and send emails to admin.

# settings.py
'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler',
            },
            'applogfile': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
            }
       },
'loggers': {
    'django': {
                'handlers': ['applogfile', 'mail_admins'],
                'level': 'ERROR',
            },
        }

We want to create custom user error page so we created a middleware to process exception:

# exceptionMiddleware.py

class ExceptionMiddleware:
    def process_exception(self, request, exception):
        message = str(exception) if isinstance(exception, BusinessLogicException) else "Sorry, we encountered an unexpected error"
        return HttpResponse( message )

The problem with this middleware is that the logging mechanism stops working. How do I get the loggers that are set up in settings.py to run from exceptionMiddleware.py?

Thanks!

Upvotes: 2

Views: 235

Answers (1)

user3628119
user3628119

Reputation: 357

Thanks to Willem's hint, here's the answer:

Set up custom error message with a generic "Sorry we encountered an error"

#urls.py

handler500 = 'mysite.views.my_custom_error_view'

and then in the middleware, only return for BusinessLogicException

#exceptionMiddleware.py

class exceptionMiddleware:
    def process_exception(self, request, exception):
        if not isinstance(exception, BusinessLogicException):
            return None
        return HttpResponse(str(exception))

Upvotes: 1

Related Questions