简体   繁体   中英

Angular $http error callback response is always undefined

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM