Created
November 11, 2013 09:45
-
-
Save nadouani/7410645 to your computer and use it in GitHub Desktop.
This is a snippet to implement a global interceptor used to handle 403 errors for example From http://stackoverflow.com/questions/17687804/handling-http-get-and-http-post-errors-in-angularjs
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('services') | |
.config(function($httpProvider){ | |
//Here we're adding our interceptor. | |
$httpProvider.responseInterceptors.push('globalInterceptor'); | |
}) | |
//Here we define our interceptor | |
.factory('globalInterceptor', function($q){ | |
//When the interceptor runs, it is passed a promise object | |
return function(promise){ | |
//In an interceptor, we return another promise created by the .then function. | |
return promise.then(function(response){ | |
//Do your code here if the response was successful | |
//Always be sure to return a response for your application code to react to as well | |
return response; | |
}, function(response){ | |
//Do your error handling code here if the response was unsuccessful | |
//Be sure to return a reject if you cannot recover from the error somehow. | |
//This way, the consumer of the $http request will know its an error as well | |
return $q.reject(response); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment