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

Throws error if undefined status code is sent #2082

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
1 change: 1 addition & 0 deletions lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,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')

/**
* schemas
Expand Down
7 changes: 6 additions & 1 deletion lib/reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ const {
FST_ERR_REP_INVALID_PAYLOAD_TYPE,
FST_ERR_REP_ALREADY_SENT,
FST_ERR_REP_SENT_VALUE,
FST_ERR_SEND_INSIDE_ONERR
FST_ERR_SEND_INSIDE_ONERR,
FST_ERR_BAD_STATUS_CODE
}
} = require('./errors')

Expand Down Expand Up @@ -197,6 +198,10 @@ Reply.prototype.headers = function (headers) {
}

Reply.prototype.code = function (code) {
if (statusCodes[code] === undefined) {
throw new FST_ERR_BAD_STATUS_CODE()
}

this.res.statusCode = code
this[kReplyHasStatusCode] = true
return this
Expand Down
30 changes: 30 additions & 0 deletions test/reply-error.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,3 +396,33 @@ test('should throw an error if the custom serializer does not serialize the payl
t.fail('should not be called')
})
})

// 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 = [
undefined,
null,
'error_code',
700 // out of the 100-600 range
]
invalidErrorCodes.forEach((invalidCode) => {
test(`should throw error if error code is ${invalidCode}`, t => {
t.plan(3)
const fastify = Fastify()
fastify.get('/', (request, reply) => {
try {
return reply.code(invalidCode).send('You should not read this')
} 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')
}
})
fastify.inject({
url: '/',
method: 'GET'
}, (e, res) => {
t.fail('should not be called')
})
})
})