from rest_framework.views import exception_handler
from rest_framework.response import Response
from utils.common_logger import logger
#### 加入日志记录,只要走到这,说明程序出error了,程序的error,咱们都要记录日志,方便后期排查
### 日志记录尽量详细:ip;如果用户登录了,记录用户;请求地址是;执行那个视图类出的错
def common_exception_handler(exc, context):
request = context.get('request')
view = context.get('view')
ip = request.META.get('REMOTE_ADDR')
try:
user_id = request.user.pk
except:
user_id = '【未登录用户】'
path = request.get_full_path()
view_str = str(view)
res = exception_handler(exc, context)#看看是否drf的异常
logger.error('用户地址为:%s,用户id号为:%s,请求地址为:%s,执行的视图函数为:%s,错误是什么:%s' % (ip, user_id, path, view_str, str(exc)))
if res:#drf的异常有两种返回方式,1.字典,2。列表
# drf的异常,一种是从res.data这个字典的detail中取,一种是 直接取data
if isinstance(res.data, dict):
msg = res.data.get('detail', None)
if not msg:
msg = res.data
data = {'code': 999, 'msg': msg}
else:
data = {'code': 998, 'msg': res.data}
else:
# django的异常
data = {'code': 888, 'msg': str(exc)}
return Response(data)
标签:get,处理,异常,str,res,msg,view,data,统一
From: https://www.cnblogs.com/dreammooncy/p/18142860