我正在清理我的代码并从回调 hell 转向 async/await 和 try/catch,但我仍然想让我的代码干燥,因为我有太多的路由并在每个请求中执行相同的 try catch。处理这个问题的最佳方法是什么?
这是我的 GET 路由之一中的示例代码。
router.get('/customer', async (req, res, next) => {
try {
const customer = await Customer.find({}).populate('buisness').exec();
return res.status(200).json({
result: customer
});
} catch (e) {
return next(e);
}
});
现在,如果我在每条路线上重复同样的事情,它就不遵循 DRY 代码。什么是最好的?
最佳答案
const errorHandlerMiddleware = async (req, res, next) => {
try {
await next();
} catch (err) {
// handle the error here
}
};
router.use(errorHandlerMiddleware);
router.get('/customer', async (req, res, next) => {
const customer = await Customer.find({}).populate('buisness').exec();
return res.status(200).json({
result: customer
});
});
在所有路由之前使用errorHandlerMiddleware
,此中间件将捕获从路由抛出的每个异常。
现在,每次您的 route 出现异常时,它都会被中间件捕获
关于node.js - 如何在nodeJS中使用异步处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732382/