Browse Source

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
http2
Sindre Sorhus 10 years ago
parent
commit
e944467ed5
  1. 4
      index.js
  2. 1
      package.json
  3. 5
      test/test-json.js

4
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);
}
}

1
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",

5
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();
});

Loading…
Cancel
Save