jmquintana79
9/24/2017 - 9:29 AM

decorator handle errors

Decorator to manage a try except validation in Python.

from functools import wraps
import logging
import sys, traceback

## decorator: handle errors (no impact on help() function)
def error(with_raise:bool = True):
    """
    Decorator to handle errors without impact on help() function
    and with the possibility to choise between raise and error
    or just print a message and return a None.
 
    with_raise -- With or without raising an error (default, True).
    return -- The main function or None or raise and error.
    """
    def _validait(func):
        @wraps(func)
        def _handle_error(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                # collect exception information
                descr = 'Function "%s()": %s'%(func.__name__,str(e))
                # collect extra information about where is the problem
                _, _, exc_tb = sys.exc_info()                
                if with_raise:
                    #logging.error(descr, exc_info=True)
                    logging.error("FILE=%s, LINE=%s" % (traceback.extract_tb(exc_tb)[-1][0], traceback.extract_tb(exc_tb)[-1][1]) ) 
                    raise 
                else:
                    logging.error(descr, exc_info=False)
                    logging.error("FILE=%s, LINE=%s" % (traceback.extract_tb(exc_tb)[-1][0], traceback.extract_tb(exc_tb)[-1][1]) ) 
                # return
                return False
        return _handle_error
    return _validait