简体   繁体   中英

How to handle `UnhandledPromiseRejectionWarning`

I have await statements which can throw errors so I am executing them inside a try/catch . However the try/catch is not catching them I get warnings:

(node:4496) UnhandledPromiseRejectionWarning: Error: Request timed out.

My code is:

(async() => {
try
{
    const result_node = nodeClient.getInfo();

}
catch (e)
{
    console.error("Error connecting to node: " + e.stack);
}
})();

I have also tried using wait-to-js . Although it catches the error I still get the error in stderr.

(async() => {
try
{
    const [err_node, result_node] = await to(nodeClient.getInfo());
        if(err_node)
            console.error("Could not connect to the Node");
}
catch (e)
{
    console.error("Error connecting to node: " + e.stack);
}
})();

What is the right way to handle errors with async/await ? Thank you.

You need to use the await keyword when you are waiting for an async call to return.

(async() => {
  try
  {
    const result_node = await nodeClient.getInfo(); // <- await keyword before the function call
  }
  catch (e)
  {
    console.error("Error connecting to node: " + e.stack);
  }
})();

try this

(async() => {
   try{
       const result_node = await nodeClient.getInfo();
   }catch (e){
       console.error("Error connecting to node: " + e.stack);
   }
})();

correct process to use async await is

var functionName = async() => {
    try
    {
        const result_node = await nodeClient.getInfo();
    }
    catch (e)
    {
        console.error("Error connecting to node: " + e);
    }
}

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