上一节给大家介绍了自定义Response返回信息,但那个只用于正确的返回success
,但是当我们用到了权限
auth 401
、方法不允许method 405
,等等,这时候我们就用自己自定义异常返回信息
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'] = []
if response.status_code == 404:
try:
response.data['message'] = response.data.pop('detail')
response.data['message'] = "Not found"
except KeyError:
response.data['message'] = "Not found"
if response.status_code == 400:
response.data['message'] = 'Input error'
elif response.status_code == 401:
response.data['message'] = "Auth failed"
elif response.status_code >= 500:
response.data['message'] = "Internal service errors"
elif response.status_code == 403:
response.data['message'] = "Access denied"
elif response.status_code == 405:
response.data['message'] = 'Request method error'
return response
#无需调用,报错的时候他自己会调用!!