自定义捕获错误
from django.db import DatabaseError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler
import logging
logger = logging.getLogger('django')
"""
此处的"django"是settings中的
# 日志对象
'loggers': {
'django': {
'handlers': ['console', 'file'], # 将来项目上线,把console去掉
'propagate': True,
},
}
"""
def custom_exception_handler(exc, context):
"""
自定义异常处理
:param exc: 异常类
:param context: 抛出异常的上下文
:return: Response响应对象
"""
# 调用drf框架原生的异常处理方法
response = exception_handler(exc, context) # context是个字典记录错误发生的具体位置,其中{'view':'记录了哪个文件,哪行报错了'}
if response is None:
view = context['view']
if isinstance(exc, DatabaseError):
# 数据库异常
# logger.error('[%s] %s' % (view, exc))
logger.error(f'{view} {exc}')
response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
标签:exc,自定义,rest,Django,framework,import,response,view From: https://www.cnblogs.com/vPYer/p/17055587.html