From c677efc48163edc765ec7b11debf0a005de1d0d4 Mon Sep 17 00:00:00 2001 From: Hoang Date: Sun, 23 May 2021 11:32:47 +0700 Subject: [PATCH] fix: handle thrown errors within async handlers (#135) * fix uncaught async error * Add test * chore: truncate * fix bad merge conflict * chore: add extra async-throw test Co-authored-by: Luke Edwards --- packages/polka/index.js | 11 +++------ packages/polka/test/index.js | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/packages/polka/index.js b/packages/polka/index.js index 0c4f83c..19f23b0 100644 --- a/packages/polka/index.js +++ b/packages/polka/index.js @@ -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 } } diff --git a/packages/polka/test/index.js b/packages/polka/test/index.js index 47f4d38..006afd3 100644 --- a/packages/polka/test/index.js +++ b/packages/polka/test/index.js @@ -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);