Skip to content

Commit

Permalink
fix: handle thrown errors within async handlers (#135)
Browse files Browse the repository at this point in the history
* fix uncaught async error

* Add test

* chore: truncate

* fix bad merge conflict

* chore: add extra async-throw test

Co-authored-by: Luke Edwards <[email protected]>
  • Loading branch information
hoangvvo and lukeed authored May 23, 2021
1 parent 66f9cc5 commit c677efc
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 8 deletions.
11 changes: 3 additions & 8 deletions packages/polka/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,9 @@ class Polka extends Router {
req.query = info.query || {};
req.search = info.search;

try {
let i=0, arr=obj.handlers.concat(this.onNoMatch), len=arr.length;
let loop = () => res.finished || (i < len) && arr[i++](req, res, next);
next = next || (err => err ? this.onError(err, req, res, next) : loop());
loop(); // init
} catch (err) {
this.onError(err, req, res, next);
}
let i=0, arr=obj.handlers.concat(this.onNoMatch), len=arr.length;
let loop = async () => res.finished || (i < len) && arr[i++](req, res, next);
(next = next || (err => err ? this.onError(err, req, res, next) : loop().catch(next)))(); // init
}
}

Expand Down
46 changes: 46 additions & 0 deletions packages/polka/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,52 @@ test('errors – `throw Error`', async () => {
});


test('errors – `throw Error` :: async', async () => {
let app = (
polka()
.use(async () => {
let err = new Error('hello');
err.code = 418;
throw err;
})
.get('/', (req, res) => {
val = 123; // wont run
res.end('OK');
})
);

let val = 42;
let uri = $.listen(app);
await get(uri).catch(err => {
assert.is(val, 42, 'exits without running route handler');
assert.is(err.statusCode, 418, '~> received custom status');
assert.is(err.data, 'hello', '~> received "hello" text');
});

app.server.close();
});

test('errors – `throw Error` :: async :: subapp', async () => {
let sub = polka().use(async () => {
throw new Error('busted');
});

let app = polka().use('/sub', sub, (req, res) => {
val = 123; // wont run
res.end('OK');
});

let val = 42;
let uri = $.listen(app);
await get(uri + '/sub/123').catch(err => {
assert.is(val, 42, 'exits without running route handler');
assert.is(err.statusCode, 500, '~> received default status');
assert.is(err.data, 'busted', '~> received "busted" text');
});

app.server.close();
});

test('errors – `throw msg`', async () => {
// t.plan(3);

Expand Down

0 comments on commit c677efc

Please sign in to comment.