まずはconfig()メソッドで$httpProviderサービスにinterceptorを追加する。
angular.module('hogeApp', []).config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('errorHttpInterceptor');
}]);
次にpushしたerrorHttpInterceptorサービスを実装する。
angular.module('hogeApp', []).factory('errorHttpInterceptor', ['$q', '$location',
function($q, $location) {
return {
// optional method
request: function(config) {
return config;
},
// optional method
requestError: function(rejection) {
return $q.reject(rejection);
},
// optional method
response: function(response) {
return response;
},
// optional method
responseError: function(rejection) {
if(rejection.status !== 200) {
// レスポンスコードに異常が見られたら処理をかますなどすきに実装する。
return $q.reject(rejection);
}
return $q.reject(rejection);
}
};
}
]);