django rest framework 自定义异常返回 包含message,code, data, result 不同与 error_messages

REST framework提供了异常处理,我们可以自定义异常处理函数。
官方文档

https://www.django-rest-framework.org/api-guide/exceptions/

REST framework定义的异常

APIException 所有异常的父类<br>
ParseError 解析错误<br>
AuthenticationFailed 认证失败<br>
NotAuthenticated 尚未认证<br>
PermissionDenied 权限决绝<br>
NotFound 未找到<br>
MethodNotAllowed 请求方式不支持<br>
NotAcceptable 要获取的数据格式不支持<br>
Throttled 超过限流次数<br>
ValidationError 校验失败

from rest_framework.exceptions import ValidationError

原文

自定义Response返回信息,但那个只用于正确的返回success,但是当我们用到了权限
auth 401、方法不允许method 405,等等,这时候我们就用自己自定义异常返回信息

django rest framework serializers error_messages 自定义

1、定义settings配置文件

#定义异常返回的路径脚本位置

REST_FRAMEWORK = {
   
    'EXCEPTION_HANDLER': 'common.utils.custom_execption.custom_exception_handler',
}


2、定义脚本

#注意,脚本路径需要与settings.py 定义的一样

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        print(response.data)
        response.data.clear()
        response.data['code'] = response.status_code
        response.data['data'] = []

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值