Skip to content

Commit

Permalink
Feature: add retryIf option (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
normartin authored Jul 25, 2022
1 parent 3745e76 commit 07949c6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export interface RetryConfig<T> {

// maximal backoff in ms (default: 5 * 60 * 1000)
maxBackOff?: number;

// allows to abort retrying for certain errors (default: () => true)
retryIf: (error: any) => boolean
}
```

Expand Down
8 changes: 8 additions & 0 deletions src/retry-promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export interface RetryConfig<T> {

// maximal backoff in ms (default: 5 * 60 * 1000)
maxBackOff: number;

// allows to abort retrying for certain errors
retryIf: (error: any) => boolean
}

const fixedBackoff = (attempt: number, delay: number) => delay;
Expand All @@ -37,6 +40,7 @@ export const defaultRetryConfig: RetryConfig<any> = {
retries: 10,
timeout: 60 * 1000,
until: () => true,
retryIf: () => true
};

export async function wait(ms: number): Promise<void> {
Expand Down Expand Up @@ -98,6 +102,10 @@ async function _retry<T>(f: () => Promise<T>, config: RetryConfig<T>, done: () =
}
config.logger("Until condition not met by " + result);
} catch (error) {
if (!config.retryIf(error)) {
throw error;
}

if (error.name === NotRetryableError.name) {
throw new RetryError(
`Met not retryable error. Last error: ${error}`,
Expand Down
25 changes: 25 additions & 0 deletions test/retry-promise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,31 @@ describe("Retry Promise", () => {
}, {retries: 1}))
.to.be.eventually.rejected.with.property("lastError", error);
});

it("should stop retrying if retryIf is false", async () => {
const failer = new Failer(1);

const result = retry(() => failer.run(), {retryIf: () => false});

await expect(result).to.eventually.be.rejected
expect(failer.calls).to.eq(1);
});

it("should provide error to retryIf function", async () => {
const error = Error("fail")
let passedError: Error | undefined;

const result = retry(() => {
throw error
}, {
retryIf: e => {
passedError = e
return false;
}
});
await expect(result).to.eventually.be.rejected;
expect(passedError).to.eq(error);
});
});

class Failer {
Expand Down

0 comments on commit 07949c6

Please sign in to comment.