Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
            }
        }
    };
like image 624
TrueWill Avatar asked Nov 30 '25 02:11

TrueWill


1 Answers

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
}
like image 145
Bergi Avatar answered Dec 02 '25 16:12

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!