How to pass try function and exception handler function in decorator way
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.
The hard-code one is like the following, but it's quite silly to add the same logic to every protocol.
for attempt in range(0, 3):
sleep_seconds = attempt ** 2
sleep(sleep_seconds)
try:
send_request(result)
break
except Exception as e:
handle_execption(e, result)