javascript - Can I catch an error from async without using await? -


can errors non-awaited async call caught, sent original encapsulating try/catch, or raise uncaught exception?

here's example of 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 scenario, error thrown fn2 swallowed silently, , not caught original try/catch. believe expected behavior, since fn2 being shoved off event loop finish @ point in future, , test doesn't care when finishes (which intentional).

is there way ensure errors not accidentally swallowed structure this, short of putting try/catch internal fn2 , doing emitting error? settle uncaught error without knowing how catch it, think -- don't expect thrown errors typical program flow writing, swallowing errors makes relatively annoying debug.

side note, i'm using babel transpile code using babel-runtime transform, , executing node.

dealing unhandled rejected native promises (and async/await uses native promises) feature supported in v8. it's used in latest chrome output debugging information when rejected promise unhandled; try following @ 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, though exception dostuff() lost (because we're not using await when call it), chrome logs rejected promise unhandled console:

screenshot

this available in node.js 4.0+, though requires listening a special unhandledrejection event:

process.on('unhandledrejection', function(reason, p) {     console.log("unhandled rejection at: promise ", p, " reason: ", reason);     // application specific logging, throwing error, or other logic here }); 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -