Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: re-thrown error crash #4488

Merged
merged 1 commit into from Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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