Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  165] [ 1]  / answers: 1 / hits: 16463  / 11 Years ago, thu, august 8, 2013, 12:00:00

I am having issues trying to gracefully handle $http errors. I am looping over a list of servers to make API calls to for status. The calls that complete successfully for perfectly. The ones that fail are not giving me access to the 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);
});
}
);


The console output shows the correct 401 error (which I didn't output) and my console error message (which I did output) with an 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 am trying to do is NOT have Angular display the 401 in the log, and instead I will display it in a graceful way. However since data is undefined I have no way of accessing the information.



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



I've also tried using $resource instead of the $http and got the exact 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.


More From » angularjs

 Answers
9

Per the $http docs, body is




The response body transformed with the transform functions.




With the 401 (Unauthorized) error you are getting back, it is quite possible there is no body being returned, hence why it is undefined.



If you want to log the error code, log the status parameter instead. It contains the HTTP Status Code, which should be uniform, unlike response bodies.


[#76451] Wednesday, August 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anjelicadixied

Total Points: 742
Total Questions: 94
Total Answers: 97

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;