Skip to content

Commit

Permalink
Handling synchronous handleTimeout function errors
Browse files Browse the repository at this point in the history
  • Loading branch information
softwarewright committed Jan 19, 2021
1 parent a172cb9 commit e7a5f12
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,13 @@ export async function retry<T> (
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (options.handleTimeout) {
resolve(options.handleTimeout(context, options));
// If calling handleTimeout throws an error that is not wrapped in a promise
// we want to catch the error and reject.
try {
resolve(options.handleTimeout(context, options));
} catch (e) {
reject(e);
}
} else {
const err: any = new Error(`Retry timeout (attemptNum: ${context.attemptNum}, timeout: ${options.timeout})`);
err.code = 'ATTEMPT_TIMEOUT';
Expand Down
13 changes: 13 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,3 +552,16 @@ test('should allow for return type to be specified', async (t) => {
t.is(result.str, 'string');
t.is(result.num, 25);
});

test('should allow handleTimeout to throw an error that can be caught', async (t) => {
const expectedError = new Error();

const actualError = await t.throws(retry(async () => {
await sleep(20);
}, {
handleTimeout: () => { throw expectedError; },
timeout: 10
}));

t.is(expectedError, actualError);
});

0 comments on commit e7a5f12

Please sign in to comment.