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'] = []