我有以下装饰器应该处理“无网络”例外:
class NetworkError(RuntimeError):
pass
def reTryer(max_retries=5, timeout=5):
def wraper(func):
request_exceptions = (
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError
)
def inner(*args, **kwargs):
for i in range(max_retries):
try:
result = func(*args, **kwargs)
except request_exceptions:
time.sleep(timeout)
print("Bad or broken connection, trying again...")
continue
else:
return result
else:
raise NetworkError
return inner
return wraper
但它完全不起作用,当我的LAN适配器处于断开连接状态时,甚至没有“连接损坏或断开,再次尝试......”输出,它只显示任何内容。这是func定义并调用:
@reTryer(5,5)
def func(arg):
#some code
func(arg)
我错过了什么吗?
答案 0 :(得分:2)
回答你的问题:
由于实施似乎是正确的,我可以想象一些可能导致问题的原因。
主要是我认为装饰的功能永远不会返回,抛出一个不同于焦点的异常,甚至恢复正常。
您可以使用
进行测试@reTryer(2, 1.0)
def always_ok():
print "ok"
@reTryer(2, 1.0)
def always_good_error():
print "good error"
raise requests.exceptions.Timeout
@reTryer(2, 1.0)
def always_bad_error():
print "bad error"
raise RuntimeError
我得到了
>>> always_ok()
ok
>>> import time
>>> always_good_error()
good error
Bad or broken connection, trying again...
good error
Bad or broken connection, trying again...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 17, in inner
__main__.NetworkError
>>> always_bad_error()
bad error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in inner
File "<stdin>", line 4, in always_bad_error
RuntimeError
>>>