Skip to content

Commit

Permalink
Merge pull request #47 from sindresorhus/parse-non-200-jsons
Browse files Browse the repository at this point in the history
Parse non-200 responses when options.json is true
  • Loading branch information
floatdrop committed Apr 8, 2015
2 parents abdd0f0 + 7da072b commit ce8b7f3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
25 changes: 25 additions & 0 deletions test/test-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit ce8b7f3

Please sign in to comment.