2017-12-30 23 views
2

私は、投稿要求を行い、データを返すサービスを持っています。角度500のエラー処理が機能しません

app.service('flagService', ['$http', function ($http) { 
this.getData = function (r, c) { 
    return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) { 
     return data; 
    }) 
} 
}]); 

そしてどこかのコントローラで

flagService.getData(row, column).then(function() { 
    console.log('it works') 
}) 

しかし、APIは500ステータスコードを返すことができます。この場合、私はコンソールで "未処理の拒否可能性"を得ます。今、私は簡単にalert()を作り、500エラーが返ってきたら開きます。私は第2の機能を含む多くの、多くのソリューションを試しました.catch().error()

app.service('flagService', ['$http', function ($http) { 
this.getData = function (r, c) { 
    return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) { 
     return data; 
    }, function (error) { 
     console.log(error) 
    }).catch(function() {console.log('error')}).error(function() {console.log('error')}) 
} 
}]); 

しかし、私はまだエラーを抱えていません。どんな解決策ですか?ありがとう!

答えて

0

グローバルなエラー処理にインターセプタを使用できます。要求が拒否されて解決されると、responseErrorが呼び出されます。

.factory('myInterceptor', ['$q', '$location', '$injector', function ($q, $location, $injector) { 
    return { 
     response: function (response) { 
      return response || $q.when(response); 
     }, 
     responseError: function (rejection) { 
      if (rejection.status === 500) { 
       console.log('http 500 response') 
      } 
      return $q.reject(rejection); 
     } 
    } 
}]) 
.config(['$httpProvider', function ($httpProvider) { 
    $httpProvider.interceptors.push('myInterceptor'); 
}]); 
関連する問題