主干错误处理

Backbone error handling

本文关键字:处理 错误      更新时间:2023-09-26

我使用主干库

服务器要求对每个请求进行授权

因此,任何对服务器的请求都可以返回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函数

服务器要求对每个请求进行授权

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

描述:在发送每个请求之前以及在$.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)
    }    
  }
}

使用self.fetch(self.options)