Skip to content

Commit

Permalink
feat: handle synchronous errors in errorHandler (#5445)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed May 5, 2024
1 parent bf64e47 commit b8cbd33
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 6 deletions.
16 changes: 10 additions & 6 deletions lib/error-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,17 @@ function handleError (reply, error, cb) {
return
}

const result = func(error, reply.request, reply)
if (result !== undefined) {
if (result !== null && typeof result.then === 'function') {
wrapThenable(result, reply)
} else {
reply.send(result)
try {
const result = func(error, reply.request, reply)
if (result !== undefined) {
if (result !== null && typeof result.then === 'function') {
wrapThenable(result, reply)
} else {
reply.send(result)
}
}
} catch (err) {
reply.send(err)
}
}

Expand Down
2 changes: 2 additions & 0 deletions lib/wrapThenable.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ function wrapThenable (thenable, reply) {
// try-catch allow to re-throw error in error handler for async handler
try {
reply.send(err)
// The following should not happen
/* c8 ignore next 3 */
} catch (err) {
reply.send(err)
}
Expand Down
32 changes: 32 additions & 0 deletions test/500s.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,35 @@ test('cannot set childLoggerFactory after binding', t => {
}
})
})

test('catch synchronous errors', t => {
t.plan(3)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.setErrorHandler((_, req, reply) => {
throw new Error('kaboom2')
})

fastify.post('/', function (req, reply) {
reply.send(new Error('kaboom'))
})

fastify.inject({
method: 'POST',
url: '/',
headers: {
'Content-Type': 'application/json'
},
payload: JSON.stringify({ hello: 'world' }).substring(0, 5)
}, (err, res) => {
t.error(err)
t.equal(res.statusCode, 500)
t.same(res.json(), {
error: 'Internal Server Error',
message: 'kaboom2',
statusCode: 500
})
})
})

0 comments on commit b8cbd33

Please sign in to comment.