Skip to content

Commit c4b9a0b

Browse files
committed
Fix stack trace for strict json parse error
1 parent dde88eb commit c4b9a0b

File tree

3 files changed

+24
-8
lines changed

3 files changed

+24
-8
lines changed

HISTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
unreleased
22
==========
33

4+
* Fix stack trace for strict json parse error
45
* deps: depd@~1.1.2
56
- perf: remove argument reassignment
67
* deps: http-errors@~1.6.3

lib/types/json.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,7 @@ function json (options) {
8888
debug('parse json')
8989
return JSON.parse(body, reviver)
9090
} catch (e) {
91-
throw normalizeJsonSyntaxError(e, {
92-
stack: e.stack
93-
})
91+
throw normalizeJsonSyntaxError(e)
9492
}
9593
}
9694

@@ -208,11 +206,10 @@ function normalizeJsonSyntaxError (error, obj) {
208206
}
209207
}
210208

211-
var props = Object.keys(obj)
212-
213-
for (var j = 0; j < props.length; j++) {
214-
var prop = props[j]
215-
error[prop] = obj[prop]
209+
if (obj) {
210+
// replace stack before message for Node.js 0.10 and below
211+
error.stack = obj.stack.replace(error.message, obj.message)
212+
error.message = obj.message
216213
}
217214

218215
return error

test/json.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,17 @@ describe('bodyParser.json()', function () {
273273
.send('true')
274274
.expect(400, 'entity.parse.failed', done)
275275
})
276+
277+
it('should include correct message in stack trace', function (done) {
278+
request(this.server)
279+
.post('/')
280+
.set('Content-Type', 'application/json')
281+
.set('X-Error-Property', 'stack')
282+
.send('true')
283+
.expect(400)
284+
.expect(shouldContainInBody(parseError('#rue').replace('#', 't')))
285+
.end(done)
286+
})
276287
})
277288
})
278289

@@ -639,3 +650,10 @@ function parseError (str) {
639650
return e.message
640651
}
641652
}
653+
654+
function shouldContainInBody (str) {
655+
return function (res) {
656+
assert.ok(res.text.indexOf(str) !== -1,
657+
'expected \'' + res.text + '\' to contain \'' + str + '\'')
658+
}
659+
}

0 commit comments

Comments
 (0)