繁体   English   中英

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

[英]jQuery Deferred object centralized global error handler

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

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

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

我正在使用最新的jQuery 3.3.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> 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM