Skip to content

Commit

Permalink
Throw a useful error if a non-error is thrown
Browse files Browse the repository at this point in the history
Fixes #14
  • Loading branch information
sindresorhus committed Mar 11, 2019
1 parent 4b6ec19 commit a9d75a5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ const pRetry = (input, options) => new Promise((resolve, reject) => {
operation.attempt(attemptNumber => Promise.resolve(attemptNumber)
.then(input)
.then(resolve, error => {
if (!(error instanceof Error)) {
reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
return;
}

if (error instanceof AbortError) {
operation.stop();
reject(error.originalError);
Expand Down
5 changes: 5 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,9 @@ test('onFailedAttempt is called before last rejection', async t => {
t.is(i, 4);
t.is(j, 4);
});

test('throws useful error message when non-error is thrown', async t => {
await t.throwsAsync(pRetry(() => {
throw 'foo'; // eslint-disable-line no-throw-literal
}), /Non-error/);
});

0 comments on commit a9d75a5

Please sign in to comment.