简体   繁体   English

在异步等待函数中引发错误后停止执行代码

[英]Stop Execution of Code After Error thrown in Async Await function

I am creating a Nodejs and express based backend application and trying to handle error in a manner which is suitable for production systems. 我正在创建一个Nodejs和基于Express的后端应用程序,并尝试以适合生产系统的方式来处理错误。

I use async await to handle all synchronous operations in the code. 我使用异步等待来处理代码中的所有同步操作。

Here is a code snippet of router end points 这是路由器端点的代码段

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")))
}

After all routes are defined I have added a common error handler that catches exceptions. 定义所有路由后,我添加了一个捕获异常的通用错误处理程序。 To simplify it I am adding a simple function 为了简化它,我添加了一个简单的函数

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

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

I expect that the code after await helper() should not execute since the exception has been handled and response sent to frontend. 我希望在等待helper()之后的代码不应该执行,因为已经处理了异常并将响应发送到前端。 Instead what I get is this error. 相反,我得到的是这个错误。

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

What is the correct way to handle error with async await? 用异步等待处理错误的正确方法是什么?

you can use try catch to handle the situation 您可以使用try catch处理情况

 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"))) } 

You get After helper is called , because your code continues to execute since it did not return 您会After helper is called得到,因为您的代码由于未return继续execute

Don't chain catch with async/await . 不要用async/await链接catch You do that with Promise . 您可以通过Promise做到这一点。

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

You can handle error like: 您可以处理如下错误:

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)
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM