Skip to content
This repository was archived by the owner on Jan 24, 2023. It is now read-only.

Commit

Permalink
onerror
Browse files Browse the repository at this point in the history
  • Loading branch information
Elmer Bulthuis committed Nov 5, 2019
1 parent ca44060 commit aa0b913
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 6 additions & 2 deletions src/retry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ test("does not retry when told not to", async (t) => {
}
},
{},
_ => (triesLeft-- > 0),
error => {
if (triesLeft-- <= 0) {
throw error;
}
},
);

t.doesNotThrow(retryLogic, "did not retry when no tries were left");
Expand All @@ -22,7 +26,7 @@ test("forwards error to caller", async (t) => {
throw new Error("InnerError");
},
{},
_ => false,
error => { throw error; },
);
} catch (err) {
t.equal(err.message, "InnerError", "error messages match");
Expand Down
11 changes: 7 additions & 4 deletions src/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const defaultRetryConfig = {
export async function retry<T>(
job: (attempt: number) => PromiseLike<T> | T,
config: RetryConfig = {},
shouldTryAgain = (error: any) => true,
onError = (error: any) => undefined as void,
control?: Promise<void>,
): Promise<T> {
const {
Expand All @@ -42,16 +42,19 @@ export async function retry<T>(
catch (error) {
if (
!(error instanceof CancelError) &&
retryAttempt < retryLimit &&
shouldTryAgain(error)
retryAttempt < retryLimit
) {
onError(error);
error = null;
}
if (error) throw error;
}

// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
intervalCurrent = Math.min(intervalCap, randomBetween(intervalBase, intervalCurrent * 3));
intervalCurrent = Math.min(
intervalCap,
randomBetween(intervalBase, intervalCurrent * 3),
);
await delay(intervalCurrent, control);

retryAttempt++;
Expand Down

0 comments on commit aa0b913

Please sign in to comment.