node.js - 如何在nodeJS中使用异步处理错误?

标签 node.js express

我正在清理我的代码并从回调 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/

相关文章:

mysql - 使用 node-mysql 和 ExpressJS 在一个请求中执行两个或多个查询

node.js - 在 Angular typescript 文件中导入 Node 模块时找不到模块错误

javascript - 在 AngularJS 应用程序中从服务器检索数据很慢

javascript - 在node js中处理跨域ajax post

Javascript 如何将 Base 64 url​​ 转换为文件?

node.js - AWS Cloud9 Lambda 安装node.js 模块

javascript - 强制 heroku 使用特定版本的 Node.js

node.js - 在node中的graphicsmagick中将PNG缓冲区转换为JPG

node.js - 从布局文件夹链接layout.pug文件

node.js - 是否有更好的依赖函数调用方法而不是堆叠它们?