gpt4 book ai didi

python - 使用装饰器在 try/except 中包装类方法

转载 作者:太空狗 更新时间:2023-10-30 02:04:11 24 4
gpt4 key购买 nike

我有一个通用功能,可以将有关异常的信息发送到应用程序日志。我在类的方法中使用 exception_handler 函数。传递给 exception_handler 并由其调用的应用程序日志处理程序创建一个 JSON 字符串,该字符串是实际发送到日志文件的内容。这一切都很好。

def exception_handler(log, terminate=False):
exc_type, exc_value, exc_tb = sys.exc_info()
filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
log.error('{0} Thrown from module: {1} in {2} at line: {3} ({4})'.format(exc_value, filename, func_name, line_num, text))
del (filename, line_num, func_name, text)
if terminate:
sys.exit()

我按如下方式使用它:(一个 super 简化的示例)

from utils import exception_handler

class Demo1(object):
def __init__(self):
self.log = {a class that implements the application log}

def demo(self, name):
try:
print(name)
except Exception:
exception_handler(self.log, True)

我想更改 exception_handler 以用作大量方法的装饰器,即:

@handle_exceptions
def func1(self, name)
{some code that gets wrapped in a try / except by the decorator}

我看了很多关于装饰器的文章,但我还没有想出如何实现我想做的事情。我需要传递对事件日志对象的引用,并将 0 个或多个参数传递给包装函数。我很乐意将 exception_handler 转换为类中的方法,如果这能让事情变得更容易的话。

最佳答案

这样的装饰器就是:

def handle_exceptions(f):
def wrapper(*args, **kw):
try:
return f(*args, **kw)
except Exception:
self = args[0]
exception_handler(self.log, True)
return wrapper

这个装饰器简单地调用了一个try 套件中的包装函数。

这只能应用于方法,因为它假定第一个参数是 self

关于python - 使用装饰器在 try/except 中包装类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23218974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com