1. 在項目的utils(改目錄需要自行創(chuàng)建)目錄中, 創(chuàng)建一個exceptions.py文件
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
from redis.exceptions import RedisError
import logging
logger = logging.getLogger('django')
def custom_exception_handler(exc, context):
"""
自定義異常處理類
:param exc: 發(fā)生異常時的異常處理對象
:param context: 拋出異常的上下文
:return: Response響應(yīng)對象
"""
response = exception_handler(exc, context)
if response is None:
view = context["view"]
if isinstance(exc, DatabaseError):
# 數(shù)據(jù)庫異常
logger.error('[%s]%s' % (view, exc))
return Response({"message": "數(shù)據(jù)庫異常"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
if isinstance(exc, RedisError):
# redis異常
logger.error('[%s]%s' % (view, exc))
return Response({"message": "redis數(shù)據(jù)庫異常"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
2. 然后在配置文件中, 注冊這個異常處理類, 在dev.py中加入如下代碼
# 數(shù)據(jù)庫異常處理
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'renranapi.utils.exceptions.custom_exception_handler',
}