Can errors from a non-awaited async call be caught, sent to an original encapsulating try/catch, or raise an uncaught exception?
Here's an example of what I mean:
async function fn1() {
console.log('executing fn1');
}
async function fn2() {
console.log('executing fn2');
throw new Error('from fn2');
}
async function test() {
try {
await fn1();
fn2();
}
catch(e) {
console.log('caught error inside test:', e);
}
}
test();
In this scenario, the error thrown from fn2
will be swallowed silently, and definitely not caught by the original try/catch
. I believe this is expected behavior, since fn2
is most likely being shoved off to the event loop to finish at some point in the future, and test
doesn't care when it finishes (which is intentional).
Is there any way to ensure that errors are not accidentally swallowed by a structure like this, short of putting a try/catch
internal to fn2
and doing something like emitting an error? I would even settle for an uncaught error without knowing how to catch it, I think -- I don't expect thrown errors to be typical program flow with what I am writing, but swallowing errors makes it relatively annoying to debug.
Side note, I'm using Babel to transpile the code using the babel-runtime transform, and executing it with node.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…