簡體   English   中英

在異步等待函數中引發錯誤后停止執行代碼

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

我正在創建一個Nodejs和基於Express的后端應用程序,並嘗試以適合生產系統的方式來處理錯誤。

我使用異步等待來處理代碼中的所有同步操作。

這是路由器端點的代碼段

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

我希望在等待helper()之后的代碼不應該執行,因為已經處理了異常並將響應發送到前端。 相反,我得到的是這個錯誤。

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

用異步等待處理錯誤的正確方法是什么?

您可以使用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"))) } 

您會After helper is called得到,因為您的代碼由於未return繼續execute

不要用async/await鏈接catch 您可以通過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)
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM