zoukankan      html  css  js  c++  java
  • 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,结束!

  • 相关阅读:
    Linux之开源软件移植
    数学问题的解题方法(模板)
    图论相关算法理解和总结
    关于ACM,关于CSU
    hdu 4607(树的直径)
    树的直径
    SGU-181 X-Sequence
    1629 B君的圆锥
    1134 最长递增子序列(暴力写的)
    1483 化学变换(暴力)
  • 原文地址:https://www.cnblogs.com/noteaddr/p/12937093.html
Copyright © 2011-2022 走看看