Retry failed requests with $http interceptor

后端 未结 3 583
無奈伤痛
無奈伤痛 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:01

    You can check for any possible server side errors by expanding the status code check a little more. This interceptor will attempt to retry the request multiple times and will do so on any response code 500 or higher. It will wait 1 second before retrying, and give up after 3 tries.

    $httpProvider.interceptors.push(function ($q, $injector) {
    
        var retries = 0,
            waitBetweenErrors = 1000,
            maxRetries = 3;
    
        function onResponseError(httpConfig) {
            var $http = $injector.get('$http');
            setTimeout(function () {
                return $http(httpConfig);
            }, waitBetweenErrors);
        }
    
        return {
            responseError: function (response) {
                if (response.status >= 500 && retries < maxRetries) {
                    retries++;
                    return onResponseError(response.config);
                }
                retries = 0;
                return $q.reject(response);
            }
        };
    });
    

提交回复
热议问题