Created
April 6, 2023 00:09
-
-
Save Grubba27/fe8f18c64821b9ef621d9a2597015005 to your computer and use it in GitHub Desktop.
simple example with retry + custom errors
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
| class RetryError extends Error { | |
| constructor(message, err) { | |
| super(message); | |
| this.kind = 'RetryError'; | |
| // work here with the error | |
| this.rawError = err; | |
| } | |
| } | |
| /** | |
| * | |
| * @param {Promise<Function>} fn | |
| * @param {*} param1 | |
| * @returns | |
| */ | |
| function retry(fn, {delay = 100, limit = 10, limitMsg = 'Retry limit reached'}){ | |
| let calls = 0; | |
| return new Promise((resolve, reject) => { | |
| const interval = setInterval(async () => { | |
| try { | |
| const result = await fn() | |
| clearInterval(interval) | |
| resolve(result) | |
| } catch (error) { | |
| if (calls >= limit) reject(new RetryError(limitMsg, err)) | |
| calls++; | |
| } | |
| },delay) | |
| }) | |
| } | |
| // usage will go like this | |
| const fn = async () => { | |
| // some code that will throw an error | |
| } | |
| try { | |
| retry(fn, {delay: 1000, limit: 10, limitMsg: 'Retry limit reached'}) | |
| } catch (e) { | |
| console.log(e.rawError, e.kind, e.message) // will have, trace, kind(RetryError) and message | |
| console.log( e instanceof Error) // true -> triggers e.g. in Sentry or React Error Boundary | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment