AngularJS。添加全局AJAX错误处理程序(如果尚未定义)

时间:2014-09-28 17:54:21

标签: javascript ajax angularjs interceptor

如果我还没有为特定的AJAX调用定义错误处理程序,我怎么能设置将被调用的全局AJAX处理程序?

如果发生错误,我的一些ajax调用确实需要做一些逻辑(例如重新启用按钮),但对于某些AJAX,我只需要在发生错误时显示错误消息。

例如,这段代码没有为AJAX调用定义任何错误处理程序,所以我想申请这个调用全局错误处理程序,我将只显示错误消息:

user.$delete().then(function () {
    // on success
});

但是这个AJAX调用已经定义了错误处理程序,我不想对它应用全局处理程序:

    $scope.deleteButtonEnabled = false;
    user.$delete().then(function () {
        // on success
    }, function(err) {   
        // Do some stuff and then show error message     
        $scope.deleteButtonEnabled = true;        
        alert('Error' + JSON.stringify(err))
    });

1 个答案:

答案 0 :(得分:5)

您可以在http调用中使用interceptors和一些配置。

定义一个拦截器: -

angular.service('HttpInterceptor', function($q){
  var service = {
     response:function(response) { //Only if you need
        //If you have to handle response data based errors you could do this here
         return $q.when(response);
      },
     responseError: function(response){
        if(!response.config.suppressGlobal){ //Handle error only if the global error handling is not suppressed
            //Handle Error based
            alert('Error' + response.status);
        }

        return $q.reject(response);
    }
  };
}).config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push('HttpInterceptor'); //Push the interceptor here
}]);

在您的服务示例中,当您进行http或资源调用时,让该方法采用可选的boolean参数来抑制全局错误处理程序,并将其与http调用的config字典参数一起传递: -

   app.service('userService', function(){
        this.getData = function(suppressGlobal){ //Take a flag to suppress globals
             return  http.get('...', {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
        };
        this.delete = function(suppressGlobal){ //Take a flag to suppress globals
          return http.delete('...', {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
        }
        this.add = function(suppressGlobal){//Take a flag to suppress globals
            return http.post('..', data, {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
        }
   });

当你打电话时: -

   // Code that needs global error handling
    user.delete().then(function () { //just call your service method as is
       // on success
    });

在其他地方: -

// Code that needs to suppress global error handling
user.delete(true).then(function () { //Pass true as argument to the delete which will supress global error handling.
    // on success
}, function(err) {   
    // Do some stuff and then show error message     
    $scope.deleteButtonEnabled = true;        
    alert('Error' + JSON.stringify(err))
});
相关问题