jmquintana79
9/24/2017 - 9:29 AM

decorator handle errors

Decorator to manage a try except validation in Python.

# decorator (no impact on help() function)
from functools import wraps
def valida(func):
    @wraps(func)
    def handle_error(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            descr = 'ERROR in "%s": %s'%(func.__name__,str(e))
            print(descr)
    return handle_error



## USAGE CASE
class bad_cat():
    def __init__(self):
        self.nya = 'meow'
 
    def art_deco(func): 
        """decorator function"""
        def handle_error(*args, **kwargs):
            try:
                return func(*args, **kwargs)
                print('we did it')
            except Exception as e:
                descr = 'failed function because of {:}'.format(e)
                print(descr)
        return handle_error
 
    @art_deco
    def launch_alert(self):
        """lanza un error cualquiera"""
        raise KeyError('oops')
 
    @art_deco
    def normal_func(self):
        """usa atributos del propio objeto"""
        k = 'cute_cat says {:}'.format(self.nya)
        print(k)
 
 
if __name__ == '__main__':
    neko = bad_cat()  # crear instancia
    neko.launch_alert()  # lanzar una funcion con error
    neko.normal_func()  # lanzar una funcion que usa atributos del objeto
    
# output:
# failed function because of 'oops'
# cute_cat says meow
# we did it