如何使用 django 中间件捕获 django rest 框架中的异常?

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

Django 中间件有一个 process_exception 钩子,可用于捕获异常和处理程序。

但是在使用 Django restframe 工作时出现了一些问题

class ExceptionHandler(MiddlewareMixin):

    @staticmethod
    def process_exception(request, exception):

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

例如,我尝试使用上面的中间件来捕获 ValidationError 和 return HTTP 400

但它不会工作并引发以下错误

AssertionError: .accepted_renderer not set on Response

原来rest-framework视图层会在response中加一个.accepted_renderer

如果我在视图外处理异常。此属性将被遗漏并导致另一个异常。

所以我的问题是:在使用django rest-framework时在中间件中处理异常是否错误?

正确的做法是什么?

在 Django Rest 框架中执行此操作的更好方法是创建自定义异常处理程序并将默认异常处理程序替换为您的自定义处理程序。有关它的更多详细信息,您可以查看官方文档:http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling