用Python,实现一个装饰器handle_error来处理有关装饰器参数的函数中的异常。

 ###### 问题遇到的现象和发生背景
实现一个装饰器handle_error来处理有关装饰器参数的函数中的异常。参数是下一个参数:∙re_raise——一个用于控制是否将从函数中重新引发异常的标志,默认为True。应该无条件地将所有不是从exc_type继承的异常重新引发;∙log_traceback-如果标志设置为True(默认情况下),将记录异常回溯。不应该处理不是从exc_type继承的所有异常;∙exc_type-异常基类型或由装饰器处理的异常基类型的非空元组(默认情况下为异常);∙尝试-如果函数引发异常(默认值1表示没有重复),则必须使用相同的参数再次调用次数。检查不允许无限尝试时提供的尝试值(例如无或负整数值);∙延迟-尝试之间的延迟(可能为浮动,默认为0);∙后退-延迟乘以尝试的值(默认情况下为1,参见下面的示例)。请注意,使用模块全局日志记录器对象是一种普通的做法。该日志记录器是日志记录的一个实例。记录器基本上。

 ###### 问题相关代码,请勿粘贴截图

Example 1
# suppress exception , log traceback
@handle_error ( re_raise = False )
def some_function (): x = 1 / 0 # ZeroDivisionError
some_function ()
print ( 1 ) # line will be executed as exception is suppressed
Example 2
# re - raise exception and doesn ’t log traceback as exc_type doesn ’t match
@handle_error ( re_raise =False , exc_type = KeyError )
def some_function (): x = 1 / 0 # ZeroDivisionError
some_function ()
print ( 1 ) # line won ’t be executed as exception is re - raised

示例3
假设随机随机()函数产生0.2、0.5、0.3个值。因此,装饰器调用一个原始的some_function,处理它,等待0.5秒,再次尝试,再等待1秒,再次尝试,最后重新引发一个异常。

import random
@handle_error ( re_raise =True , tries =3 , delay =0 .5 , backoff =2 )
def some_function ():
if random . random () < 0 . 75: x = 1 / 0 # ZeroDivisionError
some_function ()

 ###### 我想要达到的结果
用以上代码进行测试,写一下代码注释

这个问题, 我记得我回答过呀。上次悬赏好像是50块。

import logging
from time import sleep
def handle_error(re_raise = True, log_traceback = True, exc_type= Exception, tries = 1, delay = 0, backoff = 1):
    def log_decorator(f):
        def wrapper(*args, **kw):
            logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            logger = logging.getLogger(__name__)
            if log_traceback == True:
                logger.info("Start  log")
            exc_info =""
            for i in range(tries):
                exc_info = ""
                try:
                    return f(*args, **kw)
                except exc_type as e:
                    if log_traceback == True:
                        logger.error(repr(e))
                    exc_info = repr(e)
                sleep(delay*backoff)
            if re_raise == True and exc_info !="":
                print(exc_info)
        return wrapper
    return log_decorator


import random
@handle_error ( re_raise =True , tries =3 , delay =0.5 , backoff =2 )
def some_function ():
    if random.random()<0.75: x = 1 / 0 # ZeroDivisionError
some_function ()




# @handle_error(re_raise = False, log_traceback= False  )
# def some_function():
#     x = 1 / 0
#
# some_function ()
# print ( 1 ) # line will be executed as exception is suppressed

自定义一个异常类,然后利用随机数进行处理