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!!
添加回答
舉報