Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

I coding backend system with Django now, and I want control all exception from Django, so I create one middleware which name is CustomExceptoinMiddleware to control exception.

But sometimes other middleware also raise exception, I hope CustomExceptoinMiddleware can capture it too, but I don't know how to do it.

Can somebody help me?

Thanks in advance!

Python version: 3.7

Django version: 2.2.3

Setting.py

MIDDLEWARE = [

    ...

    "api.core.middleware.CustomExceptoinMiddleware ",

    "api.core.middleware.RaiseExcceptionMiddleware",

    ...

]

# middleware.py

class CustomExceptoinMiddleware(MiddlewareMixin):

    def process_exception(self, request, exception):

        print(f"Capture exception: {type(exception)}")

class RaiseExcceptionMiddleware(MiddlewareMixin):

    def process_request(self, request):

        raise KeyError()

1 Answer

0 votes
by (25.1k points)

Unfotunately, You cannot do that, you can only catch exception from the view. As stated in the official Django documentation:

Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the process_exception methods of the middleware classes above that middleware won’t be called at all.

Browse Categories

...