drf 异常处理与封装Response对象

drf 异常处理与封装Response对象

异常处理源码

def exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}
        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)
    return None

自定义异常方法

思路: 写一个方法替换掉全局,处理django自带的处理异常放回None的情况

# 自定义异常处理的方法
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def my_exception_handler(exc, context):
    '''
    exc是异常对象
	context是异常的函数和所处位置
	'''
    response=exception_handler(exc, context)
    # 两种情况,一个是None,drf没有处理
    #response对象,django处理了,但是处理的不符合咱们的要求
     if not response:
        '''
        自定义异常,可以根据exc的类型细分错误类型
        '''
        if isinstance(exc, ZeroDivisionError):
            return Response(data={'status': 777, 'msg': "除以0的错误" + str(exc)}, status=status.HTTP_400_BAD_REQUEST)

        return Response(data={'status': 999, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    return response
    
# 全局配置setting.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app01.app_auth.my_exception_handler',
}

封装Response对象

  • 封装后,更好使用
from rest_framework.response import Response
class APIResponse(Response):
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, **kwargs):
        dic = {'code': code, 'msg': msg}
        dic.update(kwargs)
        if data:
            dic['data'] = data
        super().__init__(data=dic, status=status, headers=headers)
        
使用:
return APIResponse(data={"name":'tom'})
return APIResponse(code='101',msg='错误',data={"name":'tom'},token='www',aa='yyy',header={})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

go&Python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值