我們新建一個py文件
# 在restful中導入exception_handler
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
import logging
logger = logging.getLogger("django") # 與settings中一致
def custom_exception_handler(exc, context):
"""
自定義的異常處理
:param exc: 本次請求發送的異常信息
:param context: 本次請求發送異常的執行上下文【本次請求的request對象,異常發送的時間,行號等....】
:return:
"""
response = exception_handler(exc, context)
if response is None:
"""來到這只有2中情況,要么程序沒出錯,要么就是出錯了而Django或者restframework不識別"""
view = context['view']
if isinstance(exc, DatabaseError):
# 數據庫異常
"""有5個方法發debug info error critical warning"""
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服務器內部錯誤,請聯系客服工作人員!'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
