Skip to content

Commit

Permalink
Merge pull request #40 from ndowmon/allow-async-handleError-signed-co…
Browse files Browse the repository at this point in the history
…mmits

Allow async handleError
  • Loading branch information
austin-rausch authored Oct 19, 2021
2 parents ecb6d8c + 62316ad commit d273f62
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ to your target environment.

(default: `0`)

- **`handleError`**: `(err, context, options) => void`
- **`handleError`**: `(err, context, options) => Promise<void> | void`

`handleError` is a function that will be invoked when an error occurs
for an attempt. The first argument is the error and the second
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export interface AttemptContext {
export type AttemptFunction<T> = (context: AttemptContext, options: AttemptOptions<T>) => Promise<T>;
export type BeforeAttempt<T> = (context: AttemptContext, options: AttemptOptions<T>) => void;
export type CalculateDelay<T> = (context: AttemptContext, options: AttemptOptions<T>) => number;
export type HandleError<T> = (err: any, context: AttemptContext, options: AttemptOptions<T>) => void;
export type HandleError<T> = (err: any, context: AttemptContext, options: AttemptOptions<T>) => Promise<void> | void;
export type HandleTimeout<T> = (context: AttemptContext, options: AttemptOptions<T>) => Promise<T>;

export interface AttemptOptions<T> {
Expand Down Expand Up @@ -139,7 +139,7 @@ export async function retry<T> (

const onError = async (err: any) => {
if (options.handleError) {
options.handleError(err, context, options);
await options.handleError(err, context, options);
}

if (context.aborted || (context.attemptsRemaining === 0)) {
Expand Down
20 changes: 20 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,26 @@ test('should allow attempts to be aborted via handleError', async (t) => {
t.is(err.retryable, false);
});

test('should wait for async handleError to resolve before retrying', async (t) => {
let promiseHasResolved = false;
await t.notThrows(retry(async ({ attemptNum }) => {
if (attemptNum === 0) {
throw new Error('Try again after handleError resolves.');
}
if (!promiseHasResolved) {
throw new Error('handleError has not yet resolved!');
}
return 'handleError has resolved';
}, {
delay: 0,
maxAttempts: 2,
handleError: async () => {
await sleep(1000);
promiseHasResolved = true;
}
}));
});

test('should allow handleError to return new error', async (t) => {
const err = await t.throws(retry(async (context) => {
if (context.attemptNum === 1) {
Expand Down

0 comments on commit d273f62

Please sign in to comment.