Skip to content

Commit

Permalink
feat: handle err.cause & err.stack
Browse files Browse the repository at this point in the history
This is a replacement for #49.
I just pulled out the specific change related to this issue and added it here.

Closes: expressjs/express#5630

test: Error w/ cause case

fix: recursively find Error.cause stacks

Remove the error.stack logic as it is redundant

test: check for both 1 level & 2 level Error.cause

refactor: use native util.format() API for Error printing

fix: put back original lines of code

test: update tests to be less brittle
  • Loading branch information
coltonehrman authored and wesleytodd committed Aug 31, 2024
1 parent c584cd6 commit afcdabb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* @private
*/

var util = require('util')
var debug = require('debug')('finalhandler')
var encodeUrl = require('encodeurl')
var escapeHtml = require('escape-html')
Expand Down Expand Up @@ -172,8 +173,8 @@ function getErrorMessage (err, status, env) {
var msg

if (env !== 'production') {
// use err.stack, which typically includes err.message
msg = err.stack
// use util.format to get native Error print
msg = util.format(err)

// fallback to err.toString() when possible
if (!msg && typeof err.toString === 'function') {
Expand Down
33 changes: 33 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,39 @@ var topDescribe = function (type, createServer) {
})
})
})
describe('Errors with cause', function () {
it('should return Error message with 1 level cause trace', function (done) {
var err = new Error('foo', { cause: new Error('bar') })
var expectedRegex = [/Error: foo/, /\[cause\]: Error: bar/];

request(createServer(err))
.get('/')
.then((response) => {
for (var i = 0; i < expectedRegex.length; ++i) {
var regex = expectedRegex[i];
assert.match(response.text, regex);
}
done()
})
.catch(done)
})

it('should return Error message with 2 level cause trace', function (done) {
var err = new Error('foo', { cause: new Error('bar', { cause: new Error('baz') }) })
var expectedRegex = [/Error: foo/, /\[cause\]: Error: bar/, /\[cause\]: Error: baz/];

request(createServer(err))
.get('/')
.then((response) => {
for (var i = 0; i < expectedRegex.length; ++i) {
var regex = expectedRegex[i];
assert.match(response.text, regex);
}
done()
})
.catch(done)
})
})
}

var servers = [
Expand Down

0 comments on commit afcdabb

Please sign in to comment.