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

Fixes crash when using a non-standard error code #2184

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
2 changes: 1 addition & 1 deletion lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ createError('FST_ERR_REP_ALREADY_SENT', 'Reply was already sent.')
createError('FST_ERR_REP_SENT_VALUE', 'The only possible value for reply.sent is true.')
createError('FST_ERR_SEND_INSIDE_ONERR', 'You cannot use `send` inside the `onError` hook')
createError('FST_ERR_SEND_UNDEFINED_ERR', 'Undefined error has occured')
createError('FST_ERR_BAD_STATUS_CODE', 'Called reply with malformed status code')
createError('FST_ERR_BAD_STATUS_CODE', 'Called reply with an invalid status code: %s')

/**
* schemas
Expand Down
7 changes: 4 additions & 3 deletions lib/reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,12 @@ Reply.prototype.headers = function (headers) {
}

Reply.prototype.code = function (code) {
if (statusCodes[code] === undefined) {
throw new FST_ERR_BAD_STATUS_CODE()
const intValue = parseInt(code)
if (isNaN(intValue) || intValue < 100 || intValue > 600) {
throw new FST_ERR_BAD_STATUS_CODE(String(code))
}

this.res.statusCode = code
this.res.statusCode = intValue
this[kReplyHasStatusCode] = true
return this
}
Expand Down
2 changes: 1 addition & 1 deletion test/reply-error.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ invalidErrorCodes.forEach((invalidCode) => {
} catch (err) {
t.is(err.name, 'FastifyError [FST_ERR_BAD_STATUS_CODE]')
t.is(err.code, 'FST_ERR_BAD_STATUS_CODE')
t.is(err.message, 'FST_ERR_BAD_STATUS_CODE: Called reply with malformed status code')
t.is(err.message, `FST_ERR_BAD_STATUS_CODE: Called reply with an invalid status code: ${String(invalidCode)}`)
}
})
fastify.inject({
Expand Down