Danae
Danae

Reputation: 141

Django middleware to catch exceptions

I am trying to create a Django middleware that checks whether the view raised an exception.

Could you give some example of how could there be an exception and how to process that through custom middleware.

In the end I want to store these exceptions in the database.

UPDATE: I was trying to achieve that with the login process. Which did not work.

Upvotes: 6

Views: 5213

Answers (1)

ruddra
ruddra

Reputation: 51948

Well, you can try to catch any exceptions in middleware like this:

from django.core.urlresolvers import resolve


class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        response = self.get_response(request)
        if response.status_code == 500:
            current_url = resolve(request.path_info).view_name
            content = response.content
            ExceptionHandlerModel.objects.create(url = current_url,stacktrace = content, ...) # other data you want to store here
        return response

That's about it, it won't make any sense unless you store the contents from response.content, which is full of html. So I think you should avoid this solution altogether.

Best approach would be use logger. For example in your loginview, you can try like this:

import logging
logger = logging.getLogger(__name__)

def loginview(request):
    ...
    user = authenticate(username, password)
    if not user:
        logger.error('Username {} failed to login'.format(username))

login view not necessarily throws exception either(unless you forcefully throw them). For example:

class YourAuthException(Exception):
   # defining a custom exception
   pass

# in view
if not user:
   raise YourAuthException("User login failed")

Update

def get_user(request)

    user = User.objects.get(id=99999999999)  # an id which does not exist in DB
    return HttpResponse("OK GOT IT")

Upvotes: 4

Related Questions