骨干错误处理

时间:2014-09-26 09:27:21

标签: javascript backbone.js

我使用骨干库

服务器需要每个请求的授权

因此,对服务器的任何请求都可以返回401错误

fetch()调用模型后如何处理401错误并使用相同选项调用fetch()

我在模型中使用了错误处理程序:

var Stores = Backbone.Collection.extend({
initialize: function(models, options) {
    var self = this;
    this.options = options;
    this.on({
        'error': function(model, xhr, options) {
            if (xhr.status == 401) { // Not authorized
                API.restoreToken(function() {
                    self.fetch(options);
                });
            }
        }
    });
}
});

但问题如下:当我调用self.fetch(options);时,对象options已经包含success函数。 因此,self.fetch(options);不会调用原始success函数

2 个答案:

答案 0 :(得分:2)

  

服务器需要每个请求的授权

这看起来像是一个全球性的东西所以使用$.ajaxPrefilter()非常适合。引自 here

  

说明:在发送每个请求之前以及$.ajax()处理它们之前处理自定义Ajax选项或修改现有选项。

例如,重新设置每个ajax请求的错误函数

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  // Save original function
  var originalError = options.error
  // Let's hack
  options.error = function(ejqXHR, textStatus, errorThrown){
    if(ejqXHR.status == 401) {
      API.restoreToken(function() {
        //Do magic, probably reAjax with options
        //Probably add anti-infinite-ajax mechanism
      });
    }else{ 
      //If not 401 handle it originally
      originalError(ejqXHR, textStatus, errorThrown)
    }    
  }
}

答案 1 :(得分:0)

使用self.fetch(self.options);