【发布时间】:2021-04-20 02:20:40
【问题描述】:
我希望对每条路由进行一些基本的错误处理,因此如果出现异常,API 至少会响应 500。
根据this pattern,你仍然需要在每条路由中包含一个try/catch 块:
app.post('/post', async (req, res, next) => {
const { title, author } = req.body;
try {
if (!title || !author) {
throw new BadRequest('Missing required fields: title or author');
}
const post = await db.post.insert({ title, author });
res.json(post);
} catch (err) {
next(err) // passed to the error-handling middleware
}
});
这似乎有点重复。是否有更高级别的方法可以在任何地方自动捕获异常并将其传递给中间件?
我的意思是,我显然可以定义自己的appGet():
function appGet(route, cb) {
app.get(route, async (req, res, next) => {
try {
await cb(req, res, next);
} catch (e) {
next(e);
}
});
}
有这个的内置版本吗?
【问题讨论】:
标签: node.js express error-handling middleware