django自定义错误补获

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'xxx.exception_handler',
}

新建.py文件,名称任意

 xxx.py

from django.db import DatabaseError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler


def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)

    if response is None:
        view = context['view']  # 出错的方法或者函数名称
        if isinstance(exc, DatabaseError):
            print('[%s]: %s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response

 

posted @ 2023-08-03 11:48  笑而不语心自闲  阅读(13)  评论(0编辑  收藏  举报