From c4b9a0b496e4b18876e8c9e0bb21c5749717c493 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Tue, 8 May 2018 15:31:05 -0400 Subject: [PATCH] Fix stack trace for strict json parse error --- HISTORY.md | 1 + lib/types/json.js | 13 +++++-------- test/json.js | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index d7049fe2..4c269b7d 100644 --- a/HISTORY.md +++ b/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 diff --git a/lib/types/json.js b/lib/types/json.js index a7bc838c..3fe86da1 100644 --- a/lib/types/json.js +++ b/lib/types/json.js @@ -88,9 +88,7 @@ function json (options) { debug('parse json') return JSON.parse(body, reviver) } catch (e) { - throw normalizeJsonSyntaxError(e, { - stack: e.stack - }) + throw normalizeJsonSyntaxError(e) } } @@ -208,11 +206,10 @@ 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] + if (obj) { + // 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 diff --git a/test/json.js b/test/json.js index aa96edfd..ab24cf1e 100644 --- a/test/json.js +++ b/test/json.js @@ -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) + }) }) }) @@ -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 + '\'') + } +}