在 Async Await 函数中抛出错误后停止执行代码

Kar*_*ain 5 javascript error-handling asynchronous node.js

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

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

这是路由器端点的代码片段

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")))
}
Run Code Online (Sandbox Code Playgroud)

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

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

 return res.status(500).json({error:err.name, message: err.message});
});
Run Code Online (Sandbox Code Playgroud)

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

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

使用异步等待处理错误的正确方法是什么?

156*_*223 1

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

不要catchasync/await. 你用 来做到这一点Promise

helper()
  .then(data => console.log(data))
  .catch(e => console.log(e))
Run Code Online (Sandbox Code Playgroud)

您可以处理如下错误:

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)
  }
})
Run Code Online (Sandbox Code Playgroud)