Created
November 25, 2020 15:27
-
-
Save ottomata/6177b82cb636a39fd3897e2467f50b33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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