【问题标题】:How to handle `UnhandledPromiseRejectionWarning`如何处理`UnhandledPromiseRejectionWarning`
【发布时间】:2019-12-10 17:59:54
【问题描述】:

我有await 可能引发错误的语句,所以我在try/catch 中执行它们。但是try/catch 没有捕捉到它们我收到警告:

(节点:4496)UnhandledPromiseRejectionWarning:错误:请求定时 出去。

我的代码是:

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

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

我也尝试过使用wait-to-js。虽然它捕获了错误,但我仍然在 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);
}
})();

处理async/await 错误的正确方法是什么? 谢谢。

【问题讨论】:

    标签: javascript node.js error-handling try-catch


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      使用异步等待的正确过程是

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

      【讨论】:

        【解决方案3】:

        在等待异步调用返回时,您需要使用 await 关键字。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-12
          • 2019-05-13
          • 2017-10-05
          • 2020-05-07
          • 2018-09-14
          • 1970-01-01
          相关资源
          最近更新 更多