Wilco Bakker Wilco Bakker - 1 year ago 51
Javascript Question

Error being thrown within async function gets caught

I want to use an async function instead of returning a promise, however to reject I need to throw an error like this:

async function asyncOperation() {
throw new Error("Terminate this application.");
}

(async () => {
try {
await asyncOperation();
} catch (e) {
console.error(e);
}
console.log("Nope, I am still running!"); // This will be printed regardless
})();


This means that to catch the reject I must put the function call within a try statement. By doing this, instead of terminating the application, I catch the error and I can continue afterwards.

This of course works as you would expect however I want to throw an error to actually terminate the application regardless if the function was called within a try statement or not.

How could I achieve this without checking the error within the catch statement?

Answer Source

I want to throw an error to actually terminate the application

No. Throwing exceptions is done only to be able to catch and handle them. If you really wanted to terminate your application no matter what (which would be a bad, untestable design), you'd just call process.exit() and be done with it.

I might have other errors that I do want to catch.

It sounds like what you actually want is to handle some of the thrown errors but let those that are unhandled terminate the application as usually - unless caught and handled further up in the chain. For that, you'll want to conditionally re-throw the exception:

try {
    …
    throw Object.assign(new Error("…"), {reason: X});
    …
} catch (e) {
    if (e.reason == Y) 
        console.error(e);
    else
        throw e;
}
console.log("I won't run after X errors!");

Notice that none of this actually has to do with async/await.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download