正如标题所解释的那样,我想创建一个常规异常类,以从内置的异常类继承,这些异常类稍后将在其他类中捕获。
这是我的代码:
from functools import wraps
class ControlledException(TypeError, AttributeError):
"""A generic exception on the program's domain."""
class WithRetry:
def __init__(self, retries_limit=3, allowed_exceptions=None):
self.retries_limit = retries_limit
self.allowed_exceptions = allowed_exceptions or (ControlledException,)
def __call__(self, operation):
@wraps(operation)
def wrapped(*args, **kwargs):
last_raised = None
for _ in range(self.retries_limit):
try:
return operation(*args, **kwargs)
except self.allowed_exceptions as e:
print(f'retrying {operation.__qualname__} due to {e}')
last_raised = e
raise last_raised
return wrapped
@WithRetry()
def test(x):
x = x + 1
print(x)
test('a')
ControlledExceptionclass 继承了两个异常,我想捕获它们。在这种情况下,程序将捕获 .TypeErrorAttributeErrorTypeError
我不知道为什么这个参数对(ControlledException,)没有影响。但是,如果我将(ControlledException,)更改为“异常”或“类型错误”,则会捕获错误。self.allowed_exceptions
动漫人物
相关分类