Handling exceptions and other conditions in decorators

32 Views Asked by At
def test_a():
    try:
        # If everything is working well
        return {'status': True, 'message': 'This is a problem'}
    except Exception as e:
        return {'status': False, 'message': f'Exception is raised {e}'}


def test_b(a):
    try:
        if type(a) is not int:
            return {'status': False, 'message': 'This is a problem'}
         return {'status': True, 'message': 'We are good'}
    except Exception as e:
        return {'status': False, 'message': f'Exception is raised {e}'}



if __name__ == '__main__':
    a_res = test_a()
    if not a_res['status']:
        print(test_a())

    b_res = test_a()
    if not b_res['status']:
        print(test_b())

This is the kind of approach that works well in case if I want to debug/log the results when working with a big code base.

But as the number of methods keep increasing. The number of checks that needs to be done to ensure that the method is returning true and working well can make the codebase big and redundant.

What is the elegant way to replicate the same without such verbose repetitive checks. Does the decorators help? or any design pattern that address this?

1

There are 1 best solutions below

2
TheHungryCub On

You can create a decorator to handle the error checking and logging for your functions.

def error_handler(func):
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            if isinstance(result, dict) and result.get('status') is False:
                print(result)
            return result
        except Exception as e:
            return {'status': False, 'message': f'Exception is raised {e}'}
    return wrapper

@error_handler
def test_a():
    # If everything is working well
    return {'status': True, 'message': 'This is a problem'}

@error_handler
def test_b(a):
    if type(a) is not int:
        return {'status': False, 'message': 'This is a problem'}
    return {'status': True, 'message': 'We are good'}

if __name__ == '__main__':
    print(test_a())
    print(test_b(10))

Output:

{'status': True, 'message': 'This is a problem'}
{'status': True, 'message': 'We are good'}