多代码路径下Python异常抛出的最优实现方案探讨
问题:如何在Python异常中存储描述性字符串并适配测试需求?
我用Python开发代码,采用PyTest进行测试。当前执行的任务存在多种可能的失败场景,我编写了一个执行该任务的函数用于统计各失败条件的触发次数;同时搭建了测试套件,通过特定输入测试任务各组件,断言预期的失败类型是否出现。我希望每个唯一错误都具备字符串描述,使失败条件与触发次数的映射输出具备良好的可读性。
我构思了两种实现方法:
方法1:基于异常子类的实现
class SuperException(Exception): description = "A SuperException was thrown" class CustomException1(SuperException): description = "Exception 1 was thrown" class CustomException2(SuperException): description = "Exception 2 was thrown" def func1(x): if x: raise CustomException1() raise CustomException2() def method1(): try: func1(True) except SuperException as exc: print(exc.description) def test_func1(): pytest.raises(func1, True, CustomException1) pytest.raises(func1, False, CustomException2)
这种方法为所有异常创建一个父类并定义description字段,为每个失败场景创建对应的子类。捕获SuperException类型异常时,可通过exc.description获取错误详情,也可通过PyTest的pytest.raises直接测试。但为每个失败场景定义新类的操作较为繁琐。
方法2:基于Enum+单一异常类的实现
from enum import Enum class CustomEnum(str, Enum): error1 = "First error" error2 = "Second error" class ExceptionError(Exception): """An exceptional error""" def func2(x): if x: raise ExceptionError(CustomEnum.error1) else: raise ExceptionError(CustomEnum.error2) def method2(): try: func2(True) except ExceptionError as exc: print(exc.args[0].value) def test_func2(): with pytest.raises(ExceptionError) as excinfo: func1(True) assert excinfo.args[0] == CustomEnum.error1
此方法仅定义一个异常类,将错误描述以Enum形式传入异常。捕获异常时通过exc.args[0].value获取失败信息,新增失败场景只需在Enum中添加一行,但测试步骤相对繁琐。
请问哪种方法更优?原因是什么?是否存在比这两种更好的方案?
补充:问题可简化为:如何在抛出的异常中存储这些描述性字符串?是通过子类的description字段,还是通过异常的args列表传入存储唯一字符串的Enum,或是采用异常之外的其他方式?
内容的提问来源于stack exchange,提问作者pluto_projector
相关产品推荐
相关产品推荐

