使用拦截器

时间:2016-05-23 13:50:13

标签: angularjs error-handling interceptor angular-http-interceptors

我的问题是从http REST调用处理错误的最佳方法是什么。我应该使用拦截器还是装饰器?我的休息函数看起来像这样:

    queryFunction : function (config) {
    var defer = $q.defer();
    var config = {};
    $http.get(someUrl, config) //or http.put, delete
      .then(function (response) {
        defer.resolve(response.data);
      })
      .catch(function (ex) {
        defer.reject(ex);
      });
    return defer.promise;
    },

最简单的拦截器看起来如何?

1 个答案:

答案 0 :(得分:1)

这里是通用$ http ErrorInterceptor的代码:

  app.factory('ErrorInterceptor', ['$q', function($q) {
    return {
        responseError: function(rejection) {
            // An error message is shown for all kind of server errors
            if (rejection.status == -1) {
            //alert('Backend is not working');
            //use rejection.data variable 
            }
            return $q.reject(rejection);
         }
     };
   }])

然后它可以包含在app config

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('ErrorInterceptor');
})
相关问题