繁体   English   中英

在JS中,如何捕获用户定义函数的异步调用引发的错误?

[英]In JS, how do I catch errors thrown by user-defined functions' asynchronous calls?

我正在编写一个使用用户定义函数的库。 我无法控制它们的工作,但我想抓住它们引起的所有错误。

他们还可能进行setTimeout类的异步调用,这可能会引发错误。 我也想抓住那些错误。

例如-

// Suppose this is passed as an argument to the module
var userFunction = function() {
    setTimeout(function() { throw Error("fail") }, 200);
}

// This is module code
try {
    userFunction();
} catch (e) {
    console.log("Caught error");
}

—失败,并显示堆栈跟踪。 catch不会触发。

我可以看到这种情况是如何发生的:传递给setTimeout的函数引发了错误,该函数在try - catch通过之后在不同的上下文中调用。

我该如何处理? 可能吗

如果给定的函数可以调用setTimeout或其中的其他异步进程,那么如何捕获它们可能引发的错误?

您可以使用window.onerror捕获所有错误

 try { setTimeout(function() { throw Error("fail") }, 2000); } catch (e) { console.log("Caught"); } window.onerror = function (){ document.body.innerHTML = "Test"; } 

或者您可以在异步方法中使用try catch

setTimeout(function() {
       try {
          throw Error("fail");
       } catch (e) {
        console.log("Caught");
    }
    }, 2000);

您可以使用Promises。

使用jQuery,类似:

var dfd = jQuery.Deferred();

setTimeout(function() {
  dfd.reject("some error msg");
}, 1000);

$.then(dfd.promise()).then(function() {
//blank, this is success callback
}, function(msg) {
//throw your error
});

全文: https : //api.jquery.com/deferred.promise/

编辑:可以使用任何Promise实现。 如kriswowal / q https://github.com/kriskowal/q

您不需要包括jQuery。 您可以使用Promise对象中内置的javascript:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype

你有:

y = x;

x返回一个承诺:

function() {
    ...
    return promise;
}

x中的所有异步调用都是分层的:

x是最后一个异步处理程序:

x = function () {
    ...
    // a is second to last async success handler etc..
    var j = new Promise (a);

    j.then(function() {
        // a returned resolve
        if (some successful condition) {
            resolve(what ever arguments you want to pass y);
        } else {
           reject(what ever arguments you want to pass y);
        },
        function (e) {
            // error returned by a
            reject(e);
        }
    );
    return j;
};

那么您可以执行以下操作:

y.then(function() {},
    function() {
        console.log("Caught");
    }
);

暂无
暂无

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

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