简体   繁体   中英

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

I'm writing a library that takes user-defined functions. I don't have control over what they do, but I want to catch all errors that they cause.

They might also make asynchronous calls like setTimeout , which might throw Errors. I want to catch those errors too.

For example—

// 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");
}

—fails with an error and prints a stack trace. The catch doesn't trigger.

I can see how this happens: The error is thrown from the function passed to setTimeout , which is called after the try - catch has passed, in a different context.

How do I work with that? Is it even possible?

If given a function that might call setTimeout or other asynchronous processes within it, how can I catch errors they might throw?

You can use window.onerror to catch all error

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

or you can use try catch inside async method

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

You can use Promises.

With jQuery, something like:

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
});

Full doc: https://api.jquery.com/deferred.promise/

EDIT: can use any Promise implementation. Such as kriswowal/q https://github.com/kriskowal/q

You don't need to include jQuery. You can use javascripts built in Promise object:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype

you have:

y = x;

x returns a promise:

function() {
    ...
    return promise;
}

All of the asynchronous calls in x are layered:

x is last async handler:

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;
};

then you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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