我想对每条路由进行一些基本的错误处理,所以如果有异常,API 至少会响应 500。
根据这种模式,您仍然需要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);
}
});
}
是否有一些内置版本?
