Kramer Li
Kramer Li

Reputation: 2476

How to capture exception in django rest framework with django middleware?

Django middleware have a process_exception hook which can be used to capture exception and handler.

But there is some problem while using Django restframe work

class ExceptionHandler(MiddlewareMixin):

    @staticmethod
    def process_exception(request, exception):

        if isinstance(exception, ValidationError):
            return Response(data=exception.messages, status=status.HTTP_400_BAD_REQUEST)

For example, I try to use above middleware to capture the ValidationError and return HTTP 400

But it will not work and raise below error

AssertionError: .accepted_renderer not set on Response

It turns out that the rest-framework view layer will add a .accepted_renderer to the response.

If I handle the exception outside view. This attribute will be missed and cause another exception.

So my question is: Is it wrong to handle exception in middleware when using django rest-framework?

What is the correct way to do ?

Upvotes: 1

Views: 2634

Answers (1)

Atul Mishra
Atul Mishra

Reputation: 2018

A better way to do this in Django Rest framework is to create a custom exception handler and replace the default exception handler with your custom handler. For more details on it you can check out the official documentation: http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

Upvotes: 1

Related Questions