Skip to content

Instantly share code, notes, and snippets.

@ottomata
Created November 25, 2020 15:27
Show Gist options
  • Save ottomata/6177b82cb636a39fd3897e2467f50b33 to your computer and use it in GitHub Desktop.
Save ottomata/6177b82cb636a39fd3897e2467f50b33 to your computer and use it in GitHub Desktop.
/**
* Retries calling the provided async fn up to retryLimit times.
*
* @param {Function} fn
* @param {integer} retryLimit
* Default: 1
* @param {string} customRetryWarnMessage
* If set, this message will be used in the warning log message on errors
* caught before retry limit is reached.
* @param {Object} logger
* @return {Promise} result of fn
*/
async function retryFn(fn, retryLimit = 1, customRetryWarnMessage, logger) {
for (let tryNum = 1; tryNum <= retryLimit; tryNum++) {
try {
return await fn();
} catch (error) {
if (logger) {
const warnMessage = customRetryWarnMessage || `Caught error when calling ${fn}`;
logger.warn(
{ error },
warnMessage + ` on try number ${tryNum} out of ${retryLimit}`
);
}
if (tryNum === retryLimit) {
throw error;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment