Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix($http): throw more informative error on invalid JSON response
Browse files Browse the repository at this point in the history
Fixes #15695

Closes #15724
  • Loading branch information
chirag64 authored and gkalpak committed Mar 14, 2017
1 parent c4b1c5e commit df88873
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
14 changes: 14 additions & 0 deletions docs/content/error/$http/baddata.ngdoc
@@ -0,0 +1,14 @@
@ngdoc error
@name $http:baddata
@fullName Bad JSON Data
@description

The default @{link ng.$http#default-transformations `transformResponse`} will try to parse the
response as JSON if the `Content-Type` header is `application/json` or the response looks like a
valid JSON-stringified object or array.
This error occurs when that data is not a valid JSON object.

The error message should provide additional context such as the actual response.

To resolve this error, make sure you pass valid JSON data to `transformResponse` or use an
appropriate `Content-Type` header for non-JSON data.
7 changes: 6 additions & 1 deletion src/ng/http.js
Expand Up @@ -138,7 +138,12 @@ function defaultHttpResponseTransform(data, headers) {
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
try {
data = fromJson(tempData);
} catch (e) {
throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
'Parse error: "{1}"', data, e);
}
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions test/ng/httpSpec.js
Expand Up @@ -1369,17 +1369,15 @@ describe('$http', function() {
}
);

it('should forward json deserialization errors to the http error handler',
function() {
it('should return JSON data with error message if JSON is invalid', function() {
var errCallback = jasmine.createSpy('error');

$httpBackend.expect('GET', '/url').respond('abcd', {'Content-Type': 'application/json'});
$http({method: 'GET', url: '/url'}).then(callback).catch(errCallback);
$httpBackend.expect('GET', '/url').respond('{abcd}', {'Content-Type': 'application/json'});
$http.get('/url').then(callback).catch(errCallback);
$httpBackend.flush();

expect(callback).not.toHaveBeenCalled();
expect(errCallback).toHaveBeenCalledOnce();
expect(errCallback.calls.mostRecent().args[0]).toEqual(jasmine.any(SyntaxError));
expect(errCallback.calls.mostRecent().args[0]).toEqualMinErr('$http', 'baddata');
});

});
Expand Down

0 comments on commit df88873

Please sign in to comment.