本文介绍了在try /中包装类方法,但不使用装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a general purpose function that sends info about exceptions to an application log.I use the exception_handler function from within methods in classes. The app log handler that is passed into and called by the exception_handler creates a JSON string that is what actually gets sent to the logfile. This all works fine.

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()

我使用它的方式如下:(超简化示例)

I use it as follows: (a hyper-simplified example)

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 用作装饰器,用于许多方法,即:

I would like to alter exception_handler for use as a decorator for a large number of methods, i.e.:

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

我看过关于装饰器的许多文章,但是我还没有弄清楚如何实现我想做的事情。我需要传递对活动日志对象的引用,还需要将0或多个参数传递给包装函数。如果很容易,我很乐意将 exception_handler 转换为类中的方法。

I've looked at a number of articles about decorators, but I haven't yet figured out how to implement what I want to do. I need to pass a reference to the active log object and also pass 0 or more arguments to the wrapped function. I'd be happy to convert exception_handler to a method in a class if that makes things easier.

推荐答案

这样的修饰符将是:

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 套件中的函数。

This decorator simply calls the wrapped function inside a try suite.

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

This can be applied to methods only, as it assumes the first argument is self.

这篇关于在try /中包装类方法,但不使用装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:16