Skip to content

Commit

Permalink
Throws error if an invalid status code is sent (#2082)
Browse files Browse the repository at this point in the history
Fixes: #2078
  • Loading branch information
leorossi committed Feb 13, 2020
1 parent 14b4e02 commit 41cd02f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/errors.js
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
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
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')
})
})
})

0 comments on commit 41cd02f

Please sign in to comment.