【问题标题】:Stop Execution of Code After Error thrown in Async Await function在异步等待函数中引发错误后停止执行代码
【发布时间】:2019-08-18 02:49:03
【问题描述】:

我正在创建一个基于 Nodejs 和 express 的后端应用程序,并尝试以适合生产系统的方式处理错误。

我使用 async await 来处理代码中的所有同步操作。

这里是路由器端点的代码sn-p

app.get("/demo",async (req, res, next) => {
 await helper().catch(e => return next(e))
 console.log("After helper is called")
 res.json(1)
})

function helper(){ //helper function that throws an exception
 return new Promise((resolve, reject)=> reject(new Error("Demo Error")))
}

定义完所有路由后,我添加了一个常见的错误处理程序来捕获异常。为了简化它,我添加了一个简单的函数

routes.use( (err, req, res, next) => {
  console.log("missed all", err)

 return res.status(500).json({error:err.name, message: err.message});
});

我希望 await helper() 之后的代码不应执行,因为已处理异常并将响应发送到前端。相反,我得到的是这个错误。

After helper is called
(node:46) UnhandledPromiseRejectionWarning: Error 
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the 
client

使用 async await 处理错误的正确方法是什么?

【问题讨论】:

标签: javascript node.js asynchronous error-handling


【解决方案1】:

你得到After helper is called,因为你的代码继续execute,因为它没有return

不要将catchasync/await 联系起来。你可以通过Promise 来做到这一点。

helper()
  .then(data => console.log(data))
  .catch(e => console.log(e))

你可以像这样处理错误:

app.get("/demo",async (req, res, next) => {
  try {
    await helper();
    // respond sent if all went well
    res.json(something)
  catch(e) {
    // don't need to respond as you're doing that with catch all error handler
    next(e)
  }
})

【讨论】:

    【解决方案2】:

    你可以使用trycatch来处理这种情况

    app.get("/demo",async (req, res, next) => {
     try {
      await helper()
      console.log("After helper is called")
      res.json(1)
     } catch(err) {
      next(err)
     }
    })
    
    function helper(){ //helper function that throws an exception
     return new Promise((resolve, reject)=> reject(new Error("Demo Error")))
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2019-12-30
      • 2017-12-30
      相关资源
      最近更新 更多