Skip to content

Commit

Permalink
Merge pull request #66 from AmpersandJS/optimistic-json-parser-for-er…
Browse files Browse the repository at this point in the history
…ror-responses

fix #52 parse json in error responses if possible
  • Loading branch information
naugtur committed Aug 4, 2015
2 parents 8df5d85 + 2c700a8 commit 0d3aa59
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ module.exports = function (xhr) {
var request = options.xhr = options.xhrImplementation(ajaxSettings, function (err, resp, body) {
if (err || resp.statusCode >= 400) {
if (options.error) {
try {
body = JSON.parse(body);
} catch(e){}
var message = (err? err.message : (body || "HTTP"+resp.statusCode));
options.error(resp, 'error', message);
}
Expand Down
15 changes: 15 additions & 0 deletions test/unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,21 @@ test('should call provided error callback on HTTP error.', function (t) {
});
});


test('should parse JSON in error responses if possible', function (t) {
t.plan(1);
var xhr = sync('read', modelStub(), {
error: function (resp,type,error) {
t.equal(error.e,"rror");
t.end();
},
xhrImplementation: function (ajaxSettings, callback) {
callback(null, {statusCode:400}, '{"e":"rror"}');
return {};
}
});
});

test('should call provided error callback for bad JSON.', function (t) {
t.plan(2);

Expand Down

0 comments on commit 0d3aa59

Please sign in to comment.