Skip to content Skip to sidebar Skip to footer

Wrapping Class Method In Try / Except Using Decorator

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

Solution 1:

Such a decorator would simply be:

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

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.

Solution 2:

Thanks to Martijn for pointing me in the right direction. I couldn't get his suggested solution to work but after a little more searching based on his example the following works fine:

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

Post a Comment for "Wrapping Class Method In Try / Except Using Decorator"