简体   繁体   中英

Catch error like proxy error with angularJS http service

Is it possible to catch errors like 502 Proxy Error in the $http service from Angular1? Normally the server is returning some HTTP status code like 500 and in the body an error message.

Errors like this are exactly the same of course, it's an 502 error and the body is some HTML code (default apache), so I get that HTML code as error message and my application wil show that code as error.

Is there a way to catch those errors and rewrite them to user friendly error messages?

For this you can use your own httpInterceptor kinda like this:

app.config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push('myhttpInterceptor');
}]);
app.factory('myhttpInterceptor', ['$q', '$injector', function($q, $injector){
    return {
        // optional method
        'request': function(config) {
            // do something on success
            return config;
        },

        // optional method
        'requestError': function(rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        },

        // optional method
        'response': function(response) {
            // do something on success
            return response;
        },

        // optional method
        'responseError': function(rejection) {

            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(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