我正在创建一个Nodejs和基于Express的后端应用程序,并试图以适合生产系统的方式来处理错误。
我使用async等待来处理代码中的所有同步操作。
这是路由器端点的代码段
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
使用异步等待处理错误的正确方法是什么?
答案 0 :(得分:1)
您可以使用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")))
}
答案 1 :(得分:0)
您得到After helper is called
,因为您的代码继续execute
,因为它没有return
请勿将catch
与async/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)
}
})