Skip to content

Commit c80fa1c

Browse files
chirag64gkalpak
authored andcommitted
fix($http): throw more informative error on invalid JSON response
Fixes angular#15695 Closes angular#15724
1 parent 11d9ad1 commit c80fa1c

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed

Diff for: docs/content/error/$http/baddata.ngdoc

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
@ngdoc error
2+
@name $http:baddata
3+
@fullName Bad JSON Data
4+
@description
5+
6+
The default @{link ng.$http#default-transformations `transformResponse`} will try to parse the
7+
response as JSON if the `Content-Type` header is `application/json` or the response looks like a
8+
valid JSON-stringified object or array.
9+
This error occurs when that data is not a valid JSON object.
10+
11+
The error message should provide additional context such as the actual response.
12+
13+
To resolve this error, make sure you pass valid JSON data to `transformResponse` or use an
14+
appropriate `Content-Type` header for non-JSON data.

Diff for: src/ng/http.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,12 @@ function defaultHttpResponseTransform(data, headers) {
138138
if (tempData) {
139139
var contentType = headers('Content-Type');
140140
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
141-
data = fromJson(tempData);
141+
try {
142+
data = fromJson(tempData);
143+
} catch (e) {
144+
throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
145+
'Parse error: "{1}"', data, e);
146+
}
142147
}
143148
}
144149
}

Diff for: test/ng/httpSpec.js

+4-6
Original file line numberDiff line numberDiff line change
@@ -1369,17 +1369,15 @@ describe('$http', function() {
13691369
}
13701370
);
13711371

1372-
it('should forward json deserialization errors to the http error handler',
1373-
function() {
1372+
it('should return JSON data with error message if JSON is invalid', function() {
13741373
var errCallback = jasmine.createSpy('error');
1375-
1376-
$httpBackend.expect('GET', '/url').respond('abcd', {'Content-Type': 'application/json'});
1377-
$http({method: 'GET', url: '/url'}).then(callback).catch(errCallback);
1374+
$httpBackend.expect('GET', '/url').respond('{abcd}', {'Content-Type': 'application/json'});
1375+
$http.get('/url').then(callback).catch(errCallback);
13781376
$httpBackend.flush();
13791377

13801378
expect(callback).not.toHaveBeenCalled();
13811379
expect(errCallback).toHaveBeenCalledOnce();
1382-
expect(errCallback.calls.mostRecent().args[0]).toEqual(jasmine.any(SyntaxError));
1380+
expect(errCallback.calls.mostRecent().args[0]).toEqualMinErr('$http', 'baddata');
13831381
});
13841382

13851383
});

0 commit comments

Comments
 (0)