Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created January 19, 2016 17:51
Show Gist options
  • Save tkssharma/746cd2a67f4ec5925e15 to your computer and use it in GitHub Desktop.
Save tkssharma/746cd2a67f4ec5925e15 to your computer and use it in GitHub Desktop.
Creating HTTP angular Interceptor to intercept error from server side
/**
* Angular factory on HTTP interceptor
*/
(function() {
angular.module('Codefun')
.config(function ($httpProvider, $provide) {
$provide.factory('httpInterceptor', function ($q, $rootScope, AUTH_EVENTS) {
return {
'request': function (config) {
// intercept and change config: e.g. change the URL
// for every request sending some ID token in HTTP header
if ($window.localStorage['alakarte-food.token']) {
config.headers['x-access-token'] = $window.localStorage['token'];
config.headers['x-user-id'] = $window.localStorage['user_id'];
//config.headers.Authorization = 'Token token=" ' +
// $window.localStorage['alakarte-food.token'] +'"';
}
return config || $q.when(config);
},
'response': function (response) {
// we can intercept and change response here...
// broadcasting 'httpResponse' event
//$rootScope.$broadcast('httpResponse', response);
return response || $q.when(response);
},
'requestError': function (rejection) {
// broadcasting 'httpRequestError' event
//$rootScope.$broadcast('httpRequestError', rejection);
return $q.reject(rejection);
},
'responseError': function (rejection) {
$rootScope.$broadcast({
401: AUTH_EVENTS.notAuthenticated,
}[rejection.status], rejection);
return $q.reject(rejection);
}
};
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment