Skip to content

Commit

Permalink
Prefer err.statusCode if err.status is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Jun 15, 2016
1 parent 360c1a8 commit 2e5f6b6
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 10 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ unreleased

* Change invalid or non-numeric status code to 500
* Overwrite status message to match set status code
* Prefer `err.statusCode` if `err.status` is invalid
* Set response headers from `err.headers` object
* Use `statuses` instead of `http` module for status messages
- Includes all defined status messages
Expand Down
35 changes: 25 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function finalhandler (req, res, options) {

return function (err) {
var headers = Object.create(null)
var status = res.statusCode
var status

// ignore 404 on in-flight response
if (!err && res._header) {
Expand All @@ -66,15 +66,8 @@ function finalhandler (req, res, options) {

// unhandled error
if (err) {
// respect err.statusCode
if (err.statusCode) {
status = err.statusCode
}

// respect err.status
if (err.status) {
status = err.status
}
// respect status code from error
status = getErrorStatusCode(err) || res.statusCode

// default status code to 500 if outside valid range
if (typeof status !== 'number' || status < 400 || status > 599) {
Expand Down Expand Up @@ -121,6 +114,28 @@ function finalhandler (req, res, options) {
}
}

/**
* Get status code from Error object.
*
* @param {Error} err
* @return {number}
* @private
*/

function getErrorStatusCode (err) {
// check err.status
if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
return err.status
}

// check err.statusCode
if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
return err.statusCode
}

return undefined
}

/**
* Send response.
*
Expand Down
9 changes: 9 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ describe('finalhandler(req, res)', function () {
.expect(500, done)
})

it('should use err.statusCode over invalid err.status', function (done) {
request(createServer(createError('nope', {
status: 50,
statusCode: 410
})))
.get('/')
.expect(410, done)
})

it('should ignore non-numeric err.status', function (done) {
request(createServer(createError('oops', {
status: 'oh no'
Expand Down

0 comments on commit 2e5f6b6

Please sign in to comment.