Skip to content

Commit

Permalink
Breaking: JSONClient now returns JSON parse errors. JSONP no longer s…
Browse files Browse the repository at this point in the history
…upported.
  • Loading branch information
DonutEspresso committed Feb 7, 2018
1 parent 88c1da2 commit 364e5a7
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 5,817 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Expand Up @@ -11,8 +11,7 @@ Thumbs.db
/node_modules/
npm-debug.log
/yarn.lock
package-lock.json

# build task results for ci
coverage/


23 changes: 19 additions & 4 deletions lib/JsonClient.js
Expand Up @@ -38,7 +38,10 @@ JsonClient.prototype.write = function write(options, body, callback) {
var self = this;

var bodyOrDefault = (body !== null ? body : {});
assert.object(bodyOrDefault, 'body');
assert.ok(
typeof bodyOrDefault === 'string' || typeof bodyOrDefault === 'object',
'body'
);

var resBody;
// safely stringify body if client was configured thusly
Expand All @@ -57,18 +60,22 @@ JsonClient.prototype.parse = function parse(req, callback) {
function parseResponse(err, req2, res, data) {
var obj;
var resErr = err;
var parseErr;

try {
if (data && !/^\s*$/.test(data)) {
obj = JSON.parse(data);
}
} catch (e) {
// Not really sure what else we can do here, besides
// make the client just keep going.
log.trace(e, 'Invalid JSON in response');
// bad data being returned that cannot be parsed should be surfaced
// to the caller. http errors should take precedence, but it's
// possible to receive malformed data regardless of a status code.
parseErr = e;
log.trace(parseErr, 'Invalid JSON in response');
}
obj = obj || {};

// http errors take precedence over JSON.parse errors
if (res && res.statusCode >= 400) {
// Upcast error to a RestError (if we can)
// Be nice and handle errors like
Expand Down Expand Up @@ -98,6 +105,14 @@ JsonClient.prototype.parse = function parse(req, callback) {
}
}

// if no http error but we had a json parse error, return the json
// parse err as the top level error
if (!resErr && parseErr) {
resErr = new RestError(parseErr, {
message: 'Invalid JSON in response'
});
}

if (resErr) {
resErr.body = obj;
}
Expand Down

0 comments on commit 364e5a7

Please sign in to comment.