简体   繁体   中英

Angular $http calling success on 404

I'm exposing this function through a service:

function getData(url) {
    return $http.get(url).then(function (response) {
        return response.data;
    });
}

If the call succeeds, all is good - I get back a promise that resolves as expected.

If I pass in a URL that generates a 404, I get:

TypeError: Cannot read property 'data' of undefined

on the line: return response.data;

I can see in Chrome's Developer Tools that the GET returns 404.

Why is Angular (v1.4.7, also tried with v1.5.0 ) calling my successCallback with undefined on an error?

(What I want to do is handle failures in the calling code.)

Edit: @jcaron pointed me in the right direction. The issue appears to be this configuration line (written by another developer):

$httpProvider.interceptors.push('ErrorInterceptor');

The interceptor must have a design flaw:

function ErrorInterceptor($q, $window) {
    return {
        response: function (response) {
            return response;
        },
        responseError: function (response) {
            if (response.status === 500) {
                $window.location.href = '/error';
                return $q.reject(response);
            }
        }
    };

The interceptor must have a design flaw

Indeed it has. It returns undefined in the case of a rejection that is not a 500 status, which fulfills the promise. It should be

…
responseError: function (err) {
    if (err.status === 500) {
        $window.location.href = '/error';
    }
    return $q.reject(err); // always pass on rejection
}

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