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

Roy*_*yHB 4 python decorator python-2.7 python-decorators

我有一个通用函数,它将有关异常的信息发送到应用程序日志.我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()
Run Code Online (Sandbox Code Playgroud)

我用它如下:(一个超简化的例子)

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)
Run Code Online (Sandbox Code Playgroud)

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

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

我看了很多关于装饰器的文章,但我还没弄明白如何实现我想做的事情.我需要传递对活动日志对象的引用,并将0或更多参数传递给包装函数.我很乐意转换exception_handler为类中的方法,如果这样可以使事情变得更容易.

Mar*_*ers 9

这样的装饰器就是:

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
Run Code Online (Sandbox Code Playgroud)

这个装饰器只是调用try套件中的包装函数.

这可以仅应用于方法,因为它假设第一个参数是self.