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?