diff --git a/lib/wrapThenable.js b/lib/wrapThenable.js index 7cda5d5994..b746a62e92 100644 --- a/lib/wrapThenable.js +++ b/lib/wrapThenable.js @@ -35,7 +35,13 @@ function wrapThenable (thenable, reply) { } reply[kReplyIsError] = true - reply.send(err) + + // try-catch allow to re-throw error in error handler for async handler + try { + reply.send(err) + } catch (err) { + reply.send(err) + } }) } diff --git a/test/reply-error.test.js b/test/reply-error.test.js index c9ab206eea..c4ee4fb3de 100644 --- a/test/reply-error.test.js +++ b/test/reply-error.test.js @@ -514,6 +514,34 @@ test('error thrown by custom error handler routes to default error handler', t = }) }) +// Refs: https://github.com/fastify/fastify/pull/4484#issuecomment-1367301750 +test('allow re-thrown error to default error handler when route handler is async and error handler is sync', t => { + t.plan(4) + const fastify = Fastify() + + fastify.setErrorHandler(function (error) { + t.equal(error.message, 'kaboom') + throw Error('kabong') + }) + + fastify.get('/', async function () { + throw Error('kaboom') + }) + + fastify.inject({ + url: '/', + method: 'GET' + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 500) + t.same(JSON.parse(res.payload), { + error: statusCodes['500'], + message: 'kabong', + statusCode: 500 + }) + }) +}) + // Issue 2078 https://github.com/fastify/fastify/issues/2078 // Supported error code list: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml const invalidErrorCodes = [