django/DRF(Django REST framework) 统一异常处理/输出

小熊 Python评论8,513字数 1274阅读4分14秒阅读模式

给公司一个项目加了统一的异常处理,这里简单记录一下

django/DRF(Django REST framework) 统一异常处理/输出

简单配置方法

一般我们要求每个接口统一输出,类似于如下的形式,返回码、数据、报错原因

{"status_code": 405, "data":{},"detail": "Method 'DELETE' not allowed."}

在drf中可以用中间件来做过滤,官网提供的配置方法

我直接写在urls.py 文件的头部,把所有的异常都捕获了(注意输出内容,你可以自己测试了看看)

from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.exceptions import APIException as DRFAPIException
from rest_framework.views import exception_handler as drf_exception_handler


def custom_exception_handler(exc, context):
    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})
    if isinstance(exc, Exception):
        exc = DRFAPIException(detail={'error': exc.args})

    return drf_exception_handler(exc, context)

就是在setting.py文件中,你也可以看着文档说的那在某个合适的地方

REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'myproject.urls.custom_exception_handler'
}

自定义各种错误类型

直接看 https://www.django-rest-framework.org/api-guide/exceptions/#apiexception

拓展链接

  • https://rednafi.github.io/reflections/uniform-error-response-in-django-rest-framework.html
  • https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f

weinxin
公众号
扫码订阅最新深度技术文,回复【资源】获取技术大礼包
小熊