简体   繁体   中英

How to ensure an error from an async function is captured without rethrowing the error or using Promise.reject?

Please, look at the following code. Line 5: return ex .

When I call myFunc , I expect to see 'err' in the console, but I see 'yes' which means that outside of myFunc the error is not being captured. The error is not bubbling up.

Which makes sense because I'm not rethrowing the error doing: throw ex or using Promise.reject(ex) .

My Question is: How to ensure the error is captured outside of my function without using the two methods mentioned above? Is there a way?

async function myFunc() {
    try {
        throw new Error();
    } catch (ex) {
        return ex;
    }
}

myFunc().then(() => console.log('yes')).catch(() => console.log('err'))
// 'yes'

The best way is to do this:

async function myFunc() {
    try {
        throw new Error();
    } catch (ex) {
        throw ex;
    }
}

I had an attempt at answering the question but ended up rewriting my whole answer. At one point, I deleted my answer.

As you already stated in the question, throw ex or Promise.reject(ex) are the only ways.

When I use async function in my application, I usually do so as a means to migrate away from Promise chaining and dropping then and catch . It's really odd that you mix async function but call it with Promise , then and catch syntax.

Actually, I think it's dangerous to mix it as indicated here: JavaScript Promises - reject vs. throw

If you indulge me, I want to rewrite your caller using async function and await :

 async function myFunc() { throw new Error("Some Error!"); } ( async function () { try { await myFunc(); console.log("yes"); } catch (err) { console.log("err: ", err.message); } } )(); 

This syntax is similar to its synchronous counterpart which infers we ought to use throw :

 function myFunc() { throw new Error("Some Error!"); } ( function () { try { myFunc(); console.log("yes"); } catch (err) { console.log("err: ", err.message); } } )(); 

When using async functions, you can use the normal javascript try / catch to handle errors.

If you throw within an async function, the promise it returned will be rejected. If you return from an async function (like you did in your catch block), the promise will be resolved with the returned value (in your case the exception)

Here two examples how you can handle an async function that might throw:

 // async function that might throw async function funcThatThrows() { throw new Error("IT THROWS!"); } // Exception Handling in other async functions async function example1() { try { let result = await funcThatThrows(); /* ... */ } catch(e) { console.log("example1:", e.message); } } // Exception handling in non-async functions function example2() { funcThatThrows() .then(result => { /* ... */ }) .catch(err => console.log("example2:", err.message)); } example1(); example2(); 

See Javascript Async/Await Error Handling for a detailed tutorial on async error handling :)

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