Search code examples
pythonpython-3.xerror-handlingtry-catchpython-decorators

How to perform error handling for 200 functions?


Following is a sample function

def temp(data):
    a = sample_function_1(data)
    a = a[0][0]
    b = sample_function_2(data,'no',0,30)
    b = b[-1]
    c = sample_function_3(data, 'thank', 0, None, 15, 5)
    c = c[-2]
    print(a, b, c)
    return a, b, c

Error handling is done for sample_function_1, sample_function_2, and sample_function_3 . So the values returned by these functions cause no problem but the calculations done on the variables a, b, c can throw errors.

There are more than 200 functions like this and I need to manage the errors effectively. I know that try, catch, except is an option but are there any approaches that can be taken to solve this problem.


Solution

  • With 200 functions to change everything is going to be some hard work but you could try to use a decorator, you will only be able to intercept one error per function but it may be a good compromise for your case.

    def exception_logger(func):
        wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except IndexError:
               ...doSomething...
               raise
        return wrapper
    
    @exception_logger
    def temp(data):
       ...doSomething...