Retry Loop in Python and JavaScript

Mindwatering Incorporated

Author: Tripp W Black

Created: 04/04 at 01:02 PM

 

Category:
General Web Tips
JavaScript

Task:
Implement a retry on intermittent network failures.


JavaScript Example:


let tries = 3;
for (var i = 0; i < tries; i++) {
try {
doTaskFunction();
} catch (Exception e) {
System.out.println("Failed doTaskFunction - Error: " + e.name + ", Message: " + e.message + ", Stack: " + e.stack);
if (i < 3) {
// try again
} else {
// fail and exit
System.exit(1);
// or we can throw a custom error with throw "Failed " + tries + " tries of doTaskFunction"
}
}
}


Python Example:


tries = 3
for i in range(tries):
try:
doTaskFunction()
except KeyError as e:
if i < tries - 1: # i is zero indexed
continue
else:
raise
break



previous page

×