jQuery Deferred对象集中式全局错误处理程序

时间:2018-10-11 06:53:24

标签: javascript jquery jquery-deferred

Deferred对象内部发生的错误向控制台发出警告,并且没有引起注意:

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

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

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

2 个答案:

答案 0 :(得分:2)

在阅读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>

答案 1 :(得分:0)

如果您对ajax请求使用jquery,则可以执行以下操作:

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