Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 15, 2018 16:03
Show Gist options
  • Save jonurry/001a96ee1d6f262e7a4dbf5a2665b57a to your computer and use it in GitHub Desktop.
Save jonurry/001a96ee1d6f262e7a4dbf5a2665b57a to your computer and use it in GitHub Desktop.
8.1 Retry (Eloquent JavaScript Solutions)
class MultiplicatorUnitFailure extends Error {}
function primitiveMultiply(a, b) {
if (Math.random() < 0.2) {
return a * b;
} else {
throw new MultiplicatorUnitFailure("Klunk");
}
}
function reliableMultiply(a, b) {
try {
return primitiveMultiply(a, b);
} catch (e) {
if (e instanceof MultiplicatorUnitFailure) {
return reliableMultiply(a, b);
} else {
throw e;
}
}
}
console.log(reliableMultiply(8, 8));
// → 64
@jonurry
Copy link
Author

jonurry commented Mar 15, 2018

Bugs and Errors

8.1 Retry

Say you have a function primitiveMultiply that, in 20 percent of cases, multiplies two numbers, and in the other 80 percent, raises an exception of type MultiplicatorUnitFailure. Write a function that wraps this clunky function and just keeps trying until a call succeeds, after which it returns the result.

Make sure you handle only the exceptions you are trying to handle.

@jonurry
Copy link
Author

jonurry commented Mar 15, 2018

Hints

The call to primitiveMultiply should definitely happen in a try block. The corresponding catch block should rethrow the exception when it is not an instance of MultiplicatorUnitFailure and ensure the call is retried when it is.

To do the retrying, you can either use a loop that breaks only when a call succeeds—as in the look example earlier in this chapter—or use recursion and hope you don’t get a string of failures so long that it overflows the stack (which is a pretty safe bet).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment