Retry failed requests with $http interceptor

后端 未结 3 589
無奈伤痛
無奈伤痛 2021-02-07 12:20

The API my webapp is talking to sometimes overloads and is sending 500 Internal Server Error if it cannot handle request.

There are 100+ different requests my web applic

3条回答
  •  醉酒成梦
    2021-02-07 13:11

    I wanted to retry requests in my response block also, so combining multiple answers from different posts from SO, I've written my interceptor as follows -

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push(['$rootScope', '$cookies', '$q', '$injector', function ($rootScope, $cookies, $q, $injector) {
            var retries = 0, maxRetries = 3;
    
            return {
                request: function (config) {
                    var csrf = $cookies.get("CSRF-Token");
                    config.headers['X-CSRF-Token'] = csrf;
                    if (config.data) config.data['CSRF-Token'] = csrf;
                    return config;
                },
                response: function (r) {
                    if (r.data.rCode == "000") {
                        $rootScope.serviceError = true;
                        if (retries < maxRetries) {
                            retries++;
                            var $http = $injector.get('$http');
                            return $http(r.config);
                        } else {
                            console.log('The remote server seems to be busy at the moment. Please try again in 5 minutes');
                        }
                    }
                    return r;
                },
                responseError: function (r) {
                    if (r.status === 500) {
                        if (retries < maxRetries) {
                            retries++;
                            var $http = $injector.get('$http');
                            return $http(r.config);
                        } else {
                            console.log('The remote server seems to be busy at the moment. Please try again in 5 minutes');
                        }
                    }
    
                    retries = 0;
                    return $q.reject(r);
                }
            }
        }]);
    }])
    

    credits to @S.Klechkovski, @Cameron & https://stackoverflow.com/a/20915196/5729813

提交回复
热议问题