Skip to content

Commit

Permalink
Fix exception when err cannot be converted to a string
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Feb 10, 2017
1 parent 113d8eb commit 2f5981b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
unreleased
==========

* Fix exception when `err` cannot be converted to a string
* Fully URL-encode the pathname in the 404 message
* Only include the pathname in the 404 message
* deps: debug@2.6.0
Expand Down
35 changes: 30 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function finalhandler (req, res, options) {

return function (err) {
var headers
var msg
var status

// ignore 404 on in-flight response
Expand All @@ -84,14 +85,12 @@ function finalhandler (req, res, options) {
status = getResponseStatusCode(res)
}

// production gets a basic error message
var msg = env === 'production'
? statuses[status]
: err.stack || err.toString()
msg = escapeHtml(msg)
// get error message
msg = escapeHtml(getErrorMessage(err, status, env))
.replace(NEWLINE_REGEXP, '<br>')
.replace(DOUBLE_SPACE_REGEXP, ' &nbsp;') + '\n'
} else {
// not found
status = 404
msg = 'Cannot ' + escapeHtml(req.method) +
' ' + escapeHtml(encodeUrl(parseUrl.original(req).pathname)) + '\n'
Expand Down Expand Up @@ -140,6 +139,32 @@ function getErrorHeaders (err) {
return headers
}

/**
* Get message from Error object, fallback to status message.
*
* @param {Error} err
* @param {number} status
* @param {string} env
* @return {string}
* @private
*/

function getErrorMessage (err, status, env) {
var msg

if (env !== 'production') {
// use err.stack, which typically includes err.message
msg = err.stack

// fallback to err.toString() when possible
if (!msg && typeof err.toString === 'function') {
msg = err.toString()
}
}

return msg || statuses[status]
}

/**
* Get status code from Error object.
*
Expand Down
6 changes: 6 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,12 @@ describe('finalhandler(req, res)', function () {
.expect(500, 'lame string\n', done)
})

it('should handle null prototype objects', function (done) {
request(createServer(Object.create(null)))
.get('/foo')
.expect(500, 'Internal Server Error\n', done)
})

it('should send staus code name when production', function (done) {
var err = createError('boom!', {
status: 501
Expand Down

0 comments on commit 2f5981b

Please sign in to comment.