First, abnormal module
Rewriting module object is abnormal abnormality record information (on line item).
Second, concrete placement
分析:
EXCEPTION_HANDLER arranged in drf configuration settings, the function point custom exception_handler
- drf abnormal, and will exception_handler callback function, carry the abnormal and unusual objects related content
In return exception_handler function complete exception message and exception information logging logs
例如:
#settings.py
REST_FRAMEWORK = {
# 异常模块
# 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
'EXCEPTION_HANDLER': 'api.utils.exception_handler',
}
#api/utils.py(自定义模块)
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
if response is None: # drf没有处理的异常(服务器异常)
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={
'status': 7,
'exc': '%s' % exc
})
# 项目阶段,要记录到日志文件
return Response(status=response.status_code, data={
'status': 7,
# drf处理的客户端异常,原始处理方式是将异常信息放在response对象的data中,data的格式是{'datail': '具体的异常信息'}
'exc': '%s' % response.data.get('detail')
})
核心:
Logging exception information needs to be recorded, so you need to customize.
drf only deal with clients abnormalities, abnormal server requires manual handling, uniform processing results.