2

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 ?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.