From 0f75d30d7112ec3a25e717ee28a5e8e6db7c46a3 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Tue, 8 May 2018 15:35:03 -0400 Subject: [PATCH] Fix stack trace for strict json parse error --- HISTORY.md | 1 + lib/types/json.js | 10 ++++------ test/json.js | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 6 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..2971dc14 100644 --- a/lib/types/json.js +++ b/lib/types/json.js @@ -89,6 +89,7 @@ function json (options) { return JSON.parse(body, reviver) } catch (e) { throw normalizeJsonSyntaxError(e, { + message: e.message, stack: e.stack }) } @@ -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 } 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 + '\'') + } +}