<h1>Example: $http Interceptors</h1>
<p>Interceptorを使ってグローバルのエラー処理を定義します(エラーはコンソールに表示)。</p>
<div ng-app="myApp">
  <div ng-controller="myController">
    <button ng-click="get_data('success')">成功するリクエスト</button>
    <button ng-click="get_data('error')">失敗するリクエストリクエスト</button>
    <p>{{ status }}</p>
    <p>{{ message }}</p>
  </div>
</div>
@import "bourbon";

body {
  padding: 1.5rem;
}
View Compiled
var service = angular.module("customServices", []);

service.factory('myService', ['$http', function($http) {
  return {
    data: function(type){

      //成功するリクエスト
      var success = {
        method: 'GET',
        url: 'http://api.nukos.kitchen/index.json',
        responseType: 'json'
      }
      
      //失敗するリクエスト
      var error = {
        method: 'GET',
        url: 'http://api.nukos.kitchen/error.json',
        responseType: 'json'
      }
      
      if(type == 'success'){
        var req = success;
      } else {
        var req = error;
      }

      //プロミスオブジェクトを返す
      return $http(req);
    }
  }
}]);

// Interceptors
service.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(function($q){
    return {
      request: function(config) {
        console.log('Request: ', config);
        
        return config;
      },
      requestError: function(rejection) {
        console.log('Interceptor requestError: ', rejection);
        return $q.reject(rejection);
      },
    	response: function(config) {
      	console.log('Response: ', config);
      
      	return config;
    	},
      responseError: function(rejection) {
        console.log('Interceptor responseError: ', rejection.statusText);
        return $q.reject(rejection); //結果がthen()に渡されエラー処理が実行される
      }
    }
  });
}]);


var app = angular.module('myApp', ['customServices']);
app.controller('myController', ['$scope', '$q', 'myService', function($scope, $q, myService){
  
  //データを取得後、メッセージを表示します
  $scope.get_data = function(type){
    var promise = myService.data(type);
    
    promise.then(function(strs){
      //成功時
      console.log('Success: ', strs);
      $scope.status = strs.status;
      $scope.message = strs.data.message;
      
    },function(strs){
      // Interceptorのエラー内容が表示される
      console.log('Interceptors Error: ', strs);
      
      $scope.status = strs.status;
      $scope.message = strs.statusText;
    });
  }
}]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. //ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js