【问题标题】:NodeJS. Can I handle errors in one place? Without try and catch blocks节点JS。我可以在一个地方处理错误吗?没有 try and catch 块
【发布时间】:2018-12-21 22:52:15
【问题描述】:

Node 说我应该在所有承诺中发现错误。

是否存在在一个函数中处理相同错误的良好做法? 我不想总是为所有请求编写相同的 catch 块。

我的代码如下:

(async () => {
  try {
    await makeRequest()    
  }
  catch(e) {
    console.error(e)
  }
})()

【问题讨论】:

    标签: node.js error-handling async-await


    【解决方案1】:

    试试这个:

    makeRequest()
        .catch(err => {
            // console.error(err)
        })
    

    【讨论】:

      【解决方案2】:

      对于asyncIIFE(IIAFE)错误处理执行为:

      (async () => {
        await makeRequest()    
      })().catch(console.error);
      

      请注意,在 Node.js 中,console 方法绑定到适当的上下文,因此它们可以作为回调传递。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-20
        • 1970-01-01
        • 2010-09-12
        • 1970-01-01
        • 1970-01-01
        • 2013-10-19
        • 2021-10-28
        • 1970-01-01
        相关资源
        最近更新 更多