Browse Source

Merge pull request #47 from sindresorhus/parse-non-200-jsons

Parse non-200 responses when options.json is true
http2
Vsevolod Strukchinsky 10 years ago
parent
commit
ce8b7f3a36
  1. 11
      index.js
  2. 25
      test/test-json.js

11
index.js

@ -17,7 +17,7 @@ var NestedError = require('nested-error-stacks');
function GotError(message, nested) {
NestedError.call(this, message, nested);
objectAssign(this, nested);
objectAssign(this, nested, {nested: this.nested});
}
util.inherits(GotError, NestedError);
@ -108,6 +108,15 @@ function got(url, opts, cb) {
read(res, encoding, function (err, data) {
err = new GotError(url + ' response code is ' + statusCode + ' (' + status[statusCode] + ')', err);
err.code = statusCode;
if (data && json) {
try {
data = JSON.parse(data);
} catch (e) {
err = new GotError('Parsing ' + url + ' response failed', new GotError(e.message, err));
}
}
cb(err, data, response);
});
return;

25
test/test-json.js

@ -12,6 +12,15 @@ s.on('/invalid', function (req, res) {
res.end('/');
});
s.on('/non200', function (req, res) {
res.statusCode = 500;
res.end('{"data":"dog"}');
});
s.on('/non200-invalid', function (req, res) {
res.statusCode = 500;
res.end('Internal error');
});
tape('setup', function (t) {
s.listen(s.port, function () {
@ -42,6 +51,22 @@ tape('json option wrap parsing errors', function (t) {
});
});
tape('json option should parse non-200 responses', function (t) {
got(s.url + '/non200', {json: true}, function (err, json) {
t.ok(err);
t.deepEqual(json, {data: 'dog'});
t.end();
});
});
tape('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.deepEqual(json, 'Internal error');
t.end();
});
});
tape('cleanup', function (t) {
s.close();
t.end();

Loading…
Cancel
Save