Skip to content

Commit

Permalink
Fix stack trace for strict json parse error
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed May 8, 2018
1 parent dde88eb commit 0f75d30
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
@@ -1,6 +1,7 @@
unreleased
==========

* Fix stack trace for strict json parse error
* deps: depd@~1.1.2
- perf: remove argument reassignment
* deps: http-errors@~1.6.3
Expand Down
10 changes: 4 additions & 6 deletions lib/types/json.js
Expand Up @@ -89,6 +89,7 @@ function json (options) {
return JSON.parse(body, reviver)
} catch (e) {
throw normalizeJsonSyntaxError(e, {
message: e.message,
stack: e.stack
})
}
Expand Down Expand Up @@ -208,12 +209,9 @@ function normalizeJsonSyntaxError (error, obj) {
}
}

var props = Object.keys(obj)

for (var j = 0; j < props.length; j++) {
var prop = props[j]
error[prop] = obj[prop]
}
// replace stack before message for Node.js 0.10 and below
error.stack = obj.stack.replace(error.message, obj.message)
error.message = obj.message

return error
}
Expand Down
18 changes: 18 additions & 0 deletions test/json.js
Expand Up @@ -273,6 +273,17 @@ describe('bodyParser.json()', function () {
.send('true')
.expect(400, 'entity.parse.failed', done)
})

it('should include correct message in stack trace', function (done) {
request(this.server)
.post('/')
.set('Content-Type', 'application/json')
.set('X-Error-Property', 'stack')
.send('true')
.expect(400)
.expect(shouldContainInBody(parseError('#rue').replace('#', 't')))
.end(done)
})
})
})

Expand Down Expand Up @@ -639,3 +650,10 @@ function parseError (str) {
return e.message
}
}

function shouldContainInBody (str) {
return function (res) {
assert.ok(res.text.indexOf(str) !== -1,
'expected \'' + res.text + '\' to contain \'' + str + '\'')
}
}

0 comments on commit 0f75d30

Please sign in to comment.