Skip to content

Instantly share code, notes, and snippets.

@abhijit-hota
Last active November 10, 2020 03:49
Show Gist options
  • Save abhijit-hota/646b625858377184eae33ebfc452816c to your computer and use it in GitHub Desktop.
Save abhijit-hota/646b625858377184eae33ebfc452816c to your computer and use it in GitHub Desktop.
Using generator functions in JavaScript for error handling
// Use case (?):
// Suppose you have an array of API keys from a service. We all know why you'd have multiple API keys of a single service.
// For some reason, you know that all of them are not gonna work at all times. This is the exact scenario replicated here.
// Dummy array with, let's say, dummy API keys
const api_key_array = [
"vikiohcucbigpinekjodumehdarhagbevrosolhivuvasodumsumvivahpiupaba",
"leluralcotaimgamenfukhajuzkusamubiezilezigiczaduspiwovefniuzaleh",
"wuvoneuvtucesilluleftovarkohlucukjarineetizokujunetejzaanviromdo",
"foccuseucopozecepiogaejegafpellozumoderajewtotlomkigmecaluhindig",
"gerionenifilkejepapdelpaefegogeronedtewcevsewafjubewojkaraujrari",
"gonovevwojutomuvireelipoedujobhedaluemhukkajipmiegkefamuhobjuwee",
"idukubteckergobedinihefnancufisjanalefuaradimebacvufnidujfanazuz",
"vitiicvalacpoorgesozodzufawugalenattekujicoadmokacgevnadirbughea",
];
// The generator function
function* generateKeys(limit) {
let num = -1;
while (true) {
if (num === limit) num = -1;
num++;
yield arr[num];
}
}
// Declaring the iterator that returns the array values
const limit = api_key_array.length
let generator = generateKeys(limit);
// This is the real function that uses your API service.
// Mind that this may be an infinite function if there are always errors.
// Hint: You've exhausted all of your API Keys' limits. Then this function runs for the whole day =)
function testGenerate(greeting1, greeting2) {
try {
let currentVal = generator.next().value;
// Simulate an error
let randomNum = Math.random();
if (randomNum < 0.9) throw new Error("Uh Oh. Stinky.");
// If no error occurs, use this currentVal returned by the generator function
// along with arguments passed.
console.log(`${greeting1}, ${currentVal}. ${greeting2}`);
return;
} catch (error) {
// If an error occurs, call this function again with all the arguments
console.log(error.message);
testGenerate(...arguments);
}
}
// First call to the function that uses the API key
testGenerate("Hello", "How are you?");
// More info on generator functions and using them:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
// https://javascript.info/generators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment