• drf 中 自定义 异常处理方法


    1,在项目的utils目录中,创建 exception.py :

    from rest_framework.views import exception_handler
    from rest_framework.response import Response


    def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response:
    detail = response.data.get('detail')
    non_field_errors = response.data.get('non_field_errors')
    # 异常响应
    if detail:
    return Response({'status': response.status_code, 'msg': detail, 'result': {}}) #根据status_code 来判断返回的异常的类型
    elif non_field_errors:
    return Response({'status': response.status_code, 'msg': non_field_errors[0], 'result': {}})
    else:
    # return Response({'response': '接口参数错误', 'result': {}, 'code': '', 'tips': response.data})
    return Response({'status': response.data, 'msg': '接口参数错误', 'result': {}, 'tips': response.data})

    2,在项目的settings.py 文件中,添加至全局:

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'utils.exception.custom_exception_handler',  # 自定义异常处理  
        # 分页
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
        'PAGE_SIZE': 5,
        # 查询,过滤
        'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    }

    3,结束!

  • 相关阅读:
    新人入住博客,互相交流,互相进步
    DHCP技术
    一些额外技术
    OSPF技术
    一些常用的命令
    RSTP技术及原理
    BFD原理
    VRRP技术
    Super VLAN技术
    哈希表(HashMap)
  • 原文地址:https://www.cnblogs.com/noteaddr/p/12937093.html
Copyright © 2020-2023  润新知