From e944467ed5e54ac37e19d924f17e7a1f93ebf01f Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Mon, 31 Aug 2015 15:55:57 +0700 Subject: [PATCH] improve error output on invalid JSON More descriptive error message and shows the URL of the file in question: > Unexpected token '/' at 1:1 in http://localhost:6767/invalid --- index.js | 4 +++- package.json | 1 + test/test-json.js | 5 +++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index dbe426c..749568b 100644 --- a/index.js +++ b/index.js @@ -17,6 +17,7 @@ var unzipResponse = require('unzip-response'); var createErrorClass = require('create-error-class'); var nodeStatusCodes = require('node-status-codes'); var isPlainObj = require('is-plain-obj'); +var parseJson = require('parse-json'); function requestAsEventEmitter(opts) { opts = opts || {}; @@ -90,8 +91,9 @@ function asCallback(opts, cb) { if (opts.json && statusCode !== 204) { try { - data = JSON.parse(data); + data = parseJson(data); } catch (e) { + e.fileName = urlLib.format(opts); err = new got.ParseError(e, opts); } } diff --git a/package.json b/package.json index f4b20b4..1a25d12 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "lowercase-keys": "^1.0.0", "node-status-codes": "^1.0.0", "object-assign": "^3.0.0", + "parse-json": "^2.1.0", "pinkie-promise": "^1.0.0", "prepend-http": "^1.0.0", "read-all-stream": "^3.0.0", diff --git a/test/test-json.js b/test/test-json.js index 808da03..4aba354 100644 --- a/test/test-json.js +++ b/test/test-json.js @@ -51,7 +51,8 @@ test('json option should not parse responses without a body', function (t) { test('json option wrap parsing errors', function (t) { got(s.url + '/invalid', {json: true}, function (err) { t.ok(err); - t.equal(err.message, 'Unexpected token /'); + t.ok(/Unexpected token/.test(err.message), err.message); + t.ok(err.message.indexOf(err.hostname) !== -1, err.message); t.equal(err.path, '/invalid'); t.end(); }); @@ -68,8 +69,8 @@ test('json option should parse non-200 responses', function (t) { test('json option should catch errors on invalid non-200 responses', function (t) { got(s.url + '/non200-invalid', {json: true}, function (err, json) { t.ok(err); + t.ok(/Unexpected token/.test(err.message), err.message); t.deepEqual(json, 'Internal error'); - t.equal(err.message, 'Unexpected token I'); t.equal(err.path, '/non200-invalid'); t.end(); });