Backbone 集合获取 - 使用自定义错误处理程序覆盖 ajax 错误处理程序

Backbone Collection Fetch - Override ajax error handler with custom error handler

我在一个复杂的应用程序结构中工作,我正在努力更好地处理错误。在代码中定义了一个显示错误的通用错误处理程序。

我希望我的集合/模型获取失败时更礼貌一些,并显示一条友好的错误消息。发生的事情是两者都被解雇了,但我希望以某种方式将错误标记为已处理,这样它就不会继续冒泡。

Example in jsFiddle

// generic error handler
console.log("generic error");
$(document).on('ajaxError', function( event, xhr, settings ) {
    console.log("adding generic", xhr);
    $("#errorDiv").append("<div>Generic error: " + xhr.status + " " + xhr.statusText + "</div>");
});

console.log("define collection");
var TestCollection = Backbone.Collection.extend({
    url : "http://jsfiddle.net/Kieveli/wouoxsab"
});

console.log("fetch collection");
// fetch and provide default error
var tests = new TestCollection();
tests.fetch( {
   error: function(collection, response, options) {
      console.log("adding custom", response);
      $("#errorDiv").append("<div>Custom Error: " + response.status + "</div>");

      // How to stop generic ajaxError from firing??
      console.log("options", options);
  }
 });

对于如何阻止一般错误事件的发生,您有什么想法吗?

典型的时尚,我在搜索 60 分钟后找不到答案,然后在发布后 5 分钟找到答案:

在获取选项中使用 global: false。

Javascript: How to stop multiple jQuery ajax error handlers?

http://api.jquery.com/Ajax_Events/

https://jsfiddle.net/Kieveli/wouoxsab/6/

tests.fetch( {
    global: false,
    error: function(collection, response, options) {
    console.log("adding custom", response);
    $("#errorDiv").append("<div>Custom Error: " + response.status + "</div>");

    // How to stop generic ajaxError from firing??
    console.log("options", options);
  }
 });