1 回答
TA贡献1815条经验 获得超10个赞
定义此类自定义异常时,要么必须直接使用它们,要么必须捕获原始异常,然后引发自定义异常。raise
在这里,我捕获了原始异常,抑制了它们的回溯并引发了自定义异常。
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):
for _ in range(self.retries_limit):
try:
return operation(*args, **kwargs)
# if you want to catch the error, you have to catch the original
# exceptions as opposed to custom exceptions
except (TypeError, AttributeError) as exc:
print(f"retrying {operation.__qualname__} due to {exc}")
# this suppresses the original error message and raises your
# custom exception
raise ControlledException("Here is your error message!!") from None
return wrapped
@WithRetry()
def test(x):
x = x + 1
print(x)
test("a")
这将打印出来:
retrying test due to can only concatenate str (not "int") to str
---------------------------------------------------------------------------
ControlledException Traceback (most recent call last)
<ipython-input-364-2a7d6eb73e92> in <module>
38
39
---> 40 test('a')
<ipython-input-364-2a7d6eb73e92> in wrapped(*args, **kwargs)
27 # this suppresses the original error message and raises your
28 # custom exception
---> 29 raise ControlledException('Here is your error message!!') from None
30
31 return wrapped
ControlledException: Here is your error message!!
添加回答
举报