我们新建一个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

 

相关文章:

  • 2022-12-23
  • 2021-12-12
  • 2021-07-28
  • 2022-12-23
  • 2021-09-04
  • 2022-02-27
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2022-12-23
  • 2021-04-05
  • 2021-06-12
  • 2021-11-13
相关资源
相似解决方案