zoukankan      html  css  js  c++  java
  • django项目之配置自定义异常处理类

    1、在项目的utils目录中,创建一个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: 发生异常时的异常处理对象
        :param context:  抛出异常的上下文
        :return: Response响应对象
        """
        response = exception_handler(exc, context)
        if response is None:
            view = context["view"]
            if isinstance(exc, DatabaseError):
                # 数据库异常
                logger.error('[%s]%s' % (view, exc))
                return Response({"message": "数据库异常"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
            if isinstance(exc, RedisError):
                # redis异常
                logger.error('[%s]%s' % (view, exc))
                return Response({"message": "redis数据库异常"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    2、然后再配置文件中,注册这个异常处理类,(dev.py文件中加入如下代码)

    # 数据库异常处理
    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'renranapi.utils.exceptions.custom_exception_handler',
    }
    世间安得双全法,不负如来不负卿
  • 相关阅读:
    函数之装饰器
    前端笔记之css
    前端笔记之html
    python之函数
    python之文件操作
    python基础知识
    ovirt一种基于kvm的开源虚拟化软件
    python2与3的区别
    TP框架设置验证码
    js原生子级元素阻止父级元素冒泡事件
  • 原文地址:https://www.cnblogs.com/shangguanruoling/p/12145506.html
Copyright © 2011-2022 走看看