在Async Await函数中引发错误后停止执行代码 [英] Stop Execution of Code After Error thrown in Async Await function

查看:1167
本文介绍了在Async Await函数中引发错误后停止执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a Nodejs and express based backend application and trying to handle error in a manner which is suitable for production systems.

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

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

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

I expect that the code after await helper() should not execute since the exception has been handled and response sent to frontend. 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?

推荐答案

调用帮助程序后,您得到的正确方法是什么? code>,因为您的代码继续执行,因为它没有返回

You get After helper is called, because your code continues to execute since it did not return

不要使用 async / await 链接 catch 。您可以使用 Promise

Don't chain catch with async/await. You do that with 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)
  }
})

这篇关于在Async Await函数中引发错误后停止执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆