我正在使用Express.js并尝试创建一个catchall异步错误处理程序。假设我有三条路都可能出错,
const app = express()
app.get('/user', async function(req,res) {
const res = await getUsers()
})
app.get('/questions', async function(req,res) {
const res = await getQuestions()
})
app.get('/answers', async function(req,res) {
const res = await getAnswers()
})
在这三条路由中,所有getXX函数都可能抛出错误。
我希望所有路由都只有一个异步处理程序。类似这样的东西
app.use(asyncHandler)
所以我不必尝试/捕捉每一个可能抛出错误的地方。对此有什么解决办法吗?
提前道谢!
在try/catch块中写入async/await是最佳实践。因为如果await函数抛出错误,await只接受promise的解析输出,所以它由catch块处理。
在catch块next(error)中,调用which go抛出所有后续中间件,直到找不到错误处理Minddler为止。
const app = require("../../Reference/node-post-demo/app")
app.get('/user', async function (req, res, next) {
try {
const res = await getUsers();
return res.json(res);
} catch (error) {
next(error)
}
})
app.get('/questions', async function (req, res, next) {
try {
const res = await getQuestions()
return res.json(res);
} catch (error) {
next(error)
}
})
app.get('/answers', async function (req, res, next) {
try {
const res = await getAnswers()
return res.json(res);
} catch (error) {
next(error)
}
})
app.use(async (error, req, res) => {
//here, your error hendling code
})