Created
February 19, 2014 18:51
-
-
Save stephenplusplus/9098921 to your computer and use it in GitHub Desktop.
Angular API re-attempt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('app') | |
.config(function ($httpProvider) { | |
$httpProvider.interceptors.push(['$injector', '$q', function ($injector, $q) { | |
return { | |
responseError: function (rejection) { | |
var $http = $injector.get('$http'), | |
$state = $injector.get('$state'), | |
MAX_RETRY_ATTEMPTS = 2, | |
request = rejection.config, | |
response = rejection.data, | |
retryDefer = $q.defer(), | |
retryRequest; | |
// A required API request failed. | |
if (request.__required) { | |
request.__retries = (request.__retries || 0) + 1; | |
// Keep trying. | |
if (request.__retries <= MAX_RETRY_ATTEMPTS) { | |
retryRequest = $http(request) | |
.success(function () { | |
retryDefer.resolve(retryRequest); | |
}); | |
} | |
// Last attempt. | |
if (request.__retries > MAX_RETRY_ATTEMPTS) { | |
if (response && response.message) { | |
console.error(response.message); | |
} | |
$state.go('error'); | |
retryDefer.reject(rejection); | |
} | |
return retryDefer.promise; | |
} | |
return $q.reject(rejection); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worth noting. I'm still a promise noob.