Can I catch an error from async without using await?
Dealing with unhandled rejected native promises (and async/await uses native promises) is a feature supported now in V8. It's used in the latest Chrome to output debugging information when a rejected promise is unhandled; try the following at the Babel REPL:
async function executor() {
console.log("execute");
}
async function doStuff() {
console.log("do stuff");
throw new Error("omg");
}
function handleException() {
console.error("Exception handled");
}
(async function() {
try {
await executor();
doStuff();
} catch(e) {
handleException();
}
})()
You see that, even though the exception from doStuff()
is lost (because we're not using await
when we call it), Chrome logs that a rejected promise was unhandled to the console:
This is also available in Node.js 4.0+, though it requires listening to a special unhandledRejection
event:
process.on('unhandledRejection', function(reason, p) {
console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
// application specific logging, throwing an error, or other logic here
});