首页 > 其他 > 详细

django restframework 全局异常处理,编写自定义custom_exception_handler

时间:2021-01-26 15:19:22      阅读:132      评论:0      收藏:0      [点我收藏+]
import logging
import datetime
from rest_framework.views import exception_handler as rest_handler
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework import status
logger = logging.getLogger("drf")


def exception_handler(exc, context):
    """
    :param exc: 异常
    :param context: 上下文
    :return: Response object
    """

    response = rest_handler(exc, context)
    context_view = context.get("view", None)
    context_path = context.get(‘request‘).path
    context_method = context.get(‘request‘).method
    context_ip = context.get(‘request‘).META.get("REMOTE_ADDR")
    if response is None:

        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError) or isinstance(exc, (KeyError, AttributeError)):
            logger.error(‘[ERROR] %s %s,%s‘ % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),context_view, exc))
            custom_response = Response(
                {‘success‘: False, ‘msg‘: {‘DatabaseError or RedisError‘:str(exc).replace(‘\\‘,‘‘)},
                 "status": status.HTTP_500_INTERNAL_SERVER_ERROR, "path": context_path, "method": context_method,
                 ‘remote_address‘: context_ip})
            return custom_response
    exc_detail, exc_code = exc.message, exc.status_code

    custom_response = Response({"success": False, "msg": exc_detail, "code": exc_code,
                                "path": context_path, "method": context_method, ‘remote_address‘: context_ip
                                })
    return custom_response

  

 

setting.py注册handler,

技术分享图片

 

Response body
Download
 
{
  "success": false,
  "msg": {
    "DatabaseError or RedisError": "\"None of [Index([‘internal_code‘, ‘project_name‘, ‘version_content‘, ‘version_code‘,n       ‘version_size‘, ‘requirement_link‘, ‘person_charge‘, ‘release_time‘,n       ‘release_note‘, ‘pass_rate‘, ‘bug_number‘, ‘requirement_change_number‘,n       ‘case_numbers‘],n      dtype=‘object‘)] are in the [columns]\""
  },
  "status": 500,
  "path": "/api/batch/import",
  "method": "POST",
  "remote_address": "127.0.0.1"
}

django restframework 全局异常处理,编写自定义custom_exception_handler

原文:https://www.cnblogs.com/SunshineKimi/p/14330068.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!