Skip to content

Commit

Permalink
fix: re-thrown error crash with async handler and sync custom error h…
Browse files Browse the repository at this point in the history
…andler (#4488)
  • Loading branch information
climba03003 committed Dec 29, 2022
1 parent 003eae6 commit 10fd294
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/wrapThenable.js
Expand Up @@ -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)
}
})
}

Expand Down
28 changes: 28 additions & 0 deletions test/reply-error.test.js
Expand Up @@ -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 = [
Expand Down

0 comments on commit 10fd294

Please sign in to comment.