简体   繁体   中英

How to throw error in async function and handle it only in non-immediate caller?

With regular functions in Javascript, you can have an error thrown way down the call stack and handle it in a non-immediate caller, like this:

var a = function () {
    throw new Error ("MyError!!!!");
};
var b = function () {
    a();
};

try {
    b();
} catch (e) {
    console.log ("CAUGHT!!");
}

But in async (async/await) functions it seems the error needs to be handled on every step of the way.

If I have some reusable functionality in async function, which needs to throw an error, is there a way to handle the error on a non-immediate caller (like in the example - 2 levels down the call stack instead of 1) so I don't cover with boilerplate the N functions that use it and the M functions that use those N functions?

But in async functions it seems the error needs to be handled on every step of the way.

This is not the case. Just like with Promises, simply catch at the level you need to catch the error. async functions return Promises , after all:

 var a = async function () { throw new Error ("MyError!!!!"); }; var b = async function () { await a(); }; var c = async function () { await b(); }; c().catch(e => 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