【问题标题】:jQuery Deferred object centralized global error handlerjQuery Deferred 对象集中式全局错误处理程序
【发布时间】:2018-10-11 06:53:24
【问题描述】:

Deferred 对象内部发生的错误会在控制台中引发警告,但不会在以下位置引起注意:

    window.addEventListener("error", function(e) {
       // Global handler
    });

如何使集中式错误处理程序适用于包括延迟对象在内的所有错误?

我正在使用最新的 jQuery 3.3.1,但找不到解决方案。

【问题讨论】:

  • @MaorRefaeli,这不是重复的

标签: javascript jquery jquery-deferred


【解决方案1】:

看完jQuery 3.3.1(第3605行),其实他们已经实现了$.Deferred.exceptionHook,在延迟对象失败时被调用。

对于你的情况,你只需要像这样实现它,

$.Deferred.exceptionHook = function (err, stackTrace) {
  // 'err' is what you throw in your deferred's catch.
  window.dispatchEvent( new CustomEvent('error', {
    detail: err
  }) );
}

这里有一些简单的例子。

$.Deferred.exceptionHook = function (err, stackTrace) {
  // 'err' is what you throw in your deferred's catch.
  $("#errorMessage").text(err);
}

$.when(
  $.ajax( "https://example.com" ) // This should fail since SO is sandboxed.
).then(function successFn() {
  alert("Impossible thing is happening");
}, function failFn() {
  throw "A nice error";
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<p id="errorMessage">
  
</p>

【讨论】:

  • 你是我的英雄!
  • @Jonas 请注意,我找不到任何相关文档。在使用这种方法之前,您可能需要考虑两次,因为这可能会在未来发生变化。但是 imo,这应该适用于您当前的版本。
  • 异常Hook github.com/jquery/jquery/pull/3198的相关票证
【解决方案2】:

如果您将 jquery 用于 ajax 请求,您可以这样做:

$(document).ajaxError(function(){
   console.log(arguments);
}

【讨论】:

    猜你喜欢
    • 2013-03-06
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2012-02-08
    • 1970-01-01
    • 2012-12-31
    • 2019-11-14
    相关资源
    最近更新 更多