Django自定义封装全局异常
定义异常处理类
# utils/common_exception.py
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
from .common_logger import logger
from rest_framework.exceptions import ValidationError, APIException, AuthenticationFailed
# 自定义的异常类,可以在其他地方主动抛出
class NoPermissionException(Exception):
pass
def APIException(exc, context):
# 获取异常信息上下文
request = context['request']
view = context['view']
ip = request.META['REMOTE_ADDR']
path = request.get_full_path()
method = request.method
user_id = request.user.id or '[匿名用户]'
logger.error(f"""
操作出错:{str(exc)}, 请求方式:{method}, 视图函数{view}, ip:{ip}, 访问路径:{path}, 用户:{user_id}
""")
response = drf_exception_handler(exc, context)
# 如果response存在则说明是drf的异常
if response:
logger.error(str(exc))
err = f'DRF异常:{response.data}'
code = 900
# 如果response不存在则说明是函数内部异常,需要额外细分
else:
# 这里仅做两个示例,可以根据实际情况自行添加
if isinstance(exc, NameError):
err = f'使用未引入的变量:{type(exc).__name__, str(exc)}'
code = 902
elif isinstance(exc, ZeroDivisionError):
err = f'不能除以0:{type(exc).__name__, str(exc)}'
code = 903
else:
err = f'{type(exc).__name__, str(exc)}'
code = 901
return Response({'code': code, 'msg': err})
注册到settings
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.common_exception.APIException',
}
视图抛出异常示例
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError, APIException, AuthenticationFailed
from utils.common_exception import NoPermissionException
class ExceptionViews1(APIView):
def get(self,request):
raise NoPermissionException('我是自定义异常')
class ExceptionViews2(APIView):
def get(self,request):
raise APIException('我是DRF异常')
class ExceptionViews3(APIView):
def get(self,request):
4/0