Angular $ http error callback is always undefined

I'm having trouble trying to gracefully handle $ http errors. I iterate over the list of servers to trigger API calls for status. Calls that complete successfully are excellent. Those that fail do not give me access to error information. It is always undefined. Here is the code snippet:

angular.forEach($scope.servers, function (server) { // blank out results first server.statusResults = {}; $http.jsonp(server.url + '/api/system/status?callback=JSON_CALLBACK', {headers: { 'APP-API-Key': server.apiKey }}). success(function (data, status, headers, config) { server.statusResults = data; }). error(function (data, status, headers, config) { // data is always undefined here when there is an error console.error('Error fetching feed:', data); }); } ); 

Exiting to the console shows the correct 401 error (which I did not output) and my console error message (which I did) with the undefined data object.

 GET https://server_address/api/system/status?callback=angular.callbacks._1 401 (Unauthorized) angular.min.js:104 Error fetching feed: undefined 

What I'm trying to do does NOT have Angular display 401 in the log, and instead I will show it in an elegant way. However, since the data is undefined, I do not have access to the information.

I'm new to AngularJS, but my example closely matches the other examples I found in the documentation.

I also tried using $ resource instead of $ http and got the same problem.

 var statusResource = $resource(server.url + '/api/system/status', {alt: 'json', callback: 'JSON_CALLBACK'}, { status: {method: 'JSONP'}, isArray: false, headers: { 'APP-API-Key': server.apiKey } }); // make status API call statusResource.status({}, function (data) { server.statusResults = data; }, function (err) { // data is always undefined here when there is an error console.log(err); }); 

I'm probably doing something obviously wrong, but I'm not sure what else to try.

+4
source share
1 answer

In $http docs , body is

The response body is transformed using conversion functions.

With error 401 (Unauthorized), you go back, it is possible that the body does not come back, so it is undefined.

If you want to register an error code, write down the status parameter. It contains an HTTP status code that should be uniform, unlike response bodies.

0
source

Source: https://habr.com/ru/post/1495993/


All Articles