异常处理,统一接口
#全局配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'app01.app_auth.exception_handler',
}
#统一接口的返回
#app_auth.py
# 自定义异常处理的方法
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def my_exception_handler(exc, context):
response = exception_handler(exc, context)
# 两种情况,一种是None,def没有处理
# 还有一种是response对象,django处理,但不太符合咱自己的要求
if not response:
return Response(data={'status': 999, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)
else:
# return response
return Response(data={'status': 888, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)
标签:status,exception,接口,handler,rest,import,异常,response,统一
From: https://www.cnblogs.com/zaosong/p/16972327.html