如何以装饰器方式传递try函数和异常处理函数
For example, this is the WCF
connection.
def wcf():
def send_request(result):
# establish connection...
result["response"] = True
def handle_execption(e, result):
# logger something
result["error"] = str(e)
result = []
try:
send_request(result)
except Exception as e:
handle_execption(e, result)
Now, I want to add a retry mechanism to this connection.
What is the best way to achieve that, I have multiple connection ways(like REST
, SOAP
WCF
, etc)? In general, they share the same pattern and all have the send_request
and handle_execption
.
硬编码类似于以下内容,但是向每个协议添加相同的逻辑是很愚蠢的。
for attempt in range(0, 3):
sleep_seconds = attempt ** 2
if sleep_seconds:
sleep(sleep_seconds)
attempt += 1
try:
send_request(result)
break
except Exception as e:
handle_execption(e, result)