Packing class method in try / except using decorator

I have a general purpose function that sends exception information to the application log. I use a function exception_handlerfrom methods in classes. The application log handler, which is passed and called exception_handler, creates a JSON string that is actually sent to the log file. All of this works great.

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: (example with 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)

I would like to change exception_handlerto use as a decorator for a large number of methods, that is:

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

, , , . , 0 . exception_handler , .

+4
2

:

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.

+8

Martijn , . , , , :

def handle_exceptions(fn):
    from functools import wraps
    @wraps(fn)
    def wrapper(self, *args, **kw):
        try:
            return fn(self, *args, **kw)
        except Exception:
            exception_handler(self.log)
    return wrapper
0

Source: https://habr.com/ru/post/1537499/


All Articles