Dvoyni
Dvoyni

Reputation: 5578

Django: send error to admin and return response to user

I have got JSON API (as the part of the project) implemented with Django. Sometimes I return error to user in JSON form. I want to notify admin via standard error reporting procedure via email (for example when uncaught exception raised). But I want to return some JSON response too, not 500 error page. Some metacode to make sure that everything clear:

def request_handler(request):
    try:
        code_that_rises_an_exception()
        return response('{"result":"success"}')
    except Exception,e:
        notify_admin_about_error(e)           # <- this function is required
        return response('{"result":"error"}')

Thank you!

Upvotes: 1

Views: 1128

Answers (1)

praveen
praveen

Reputation: 3263

You can use Django Middleware for this. Middlewares allow you to modify/process Django's HttpRequest object that is supplied to a view and HttpResponse object that is returned by a view as well as take action when a view raises an exception. You can do variety of tasks with this such as logging of the meta data of the requests you receive, error reporting etc. Django calls process_exception whenever an exception is raised by a view and you can define process_exception() to send a mail to you whenever an exception gets raised.

class ErrorReportingMiddleware(object):
    def process_exception(self, request, exception):
        send_mail_to_admin(exception) # you can collect some more information here
        return HttpResponse('{"result":"error"}') # this response is returned to the user

Add this class to your MIDDLEWARE_CLASSES variable in settings.py at the end of that tuple.

Your view would reduce to:

def request_handler(request):
    code_that_rises_an_exception()
    return response('{"result":"success"}')

Now if an exception is raised by request_handler, Django would call process_exception method of your ErrorReportingMiddleware which will send a mail to the admin about the exception and return a JSON response to the browser instead of a 500 page. I would implement send_mail_to_admin as an asynchronous function so that the processing of the response by django doesn't get blocked due to sending of mail and quick response is returned to the user.

Upvotes: 1

Related Questions