在装饰器中处理异常和其他条件

问题描述 投票:0回答:1
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())

如果我想在使用大型代码库时调试/记录结果,这种方法非常有效。

但是随着方法数量不断增加。为了确保该方法返回 true 并正常工作而需要进行的检查数量可能会使代码库变得庞大且冗余。

在没有如此冗长的重复检查的情况下复制相同内容的优雅方法是什么? 装饰器有帮助吗?或任何解决这个问题的设计模式?

python-3.x exception python-decorators
1个回答
0
投票

您可以创建一个装饰器来处理函数的错误检查和日志记录。

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))

输出:

{'status': True, 'message': 'This is a problem'}
{'status': True, 'message': 'We are good'}
© www.soinside.com 2019 - 2024. All rights reserved.