【问题标题】:Custom Error Handler not working in NodeJs Express自定义错误处理程序在 NodeJs Express 中不起作用
【发布时间】:2022-02-08 14:46:32
【问题描述】:

我正在研究 express 中的错误处理,我定义了一个。它适用于非异步函数。但是当涉及到异步功能时,应用程序就会崩溃。

app.get("/products/:id", async (req, res, next) => {
  const { id } = req.params;
  const product = await Product.findById(id);
  if (!product) {
    return next(new AppError());
  }
  res.render("products/show", { product });
});

我已将错误处理程序放在应用程序的底部,如下所示:

app.use((err, req, res, next) => {
  const { status = 500, message = "something went wrong" } = err;
  res.status(status).send(message);
});

我的自定义错误类:

class AppError extends Error {
  constructor(message, status) {
    super();
    this.message = message;
    this.status = status;
  }
}

module.exports = AppError;

【问题讨论】:

    标签: node.js express error-handling


    【解决方案1】:

    我相信您的路由器不知道当等待由于任何原因而失败时该怎么做。您可以使用我在下面创建的这个 catchAsync,但您也可以在代码周围执行 try catch 语句,以便捕获错误并继续下一个任务。

    try/catch 可能看起来像这样

    app.get("/products/:id", async (req, res, next) => {
      try{
        const { id } = req.params;
        const product = await Product.findById(id);
        res.render("products/show", { product });
        
      } catch(err) {
        return next(new AppError());
      }
    });
    

    这是我可以使用的 catch 异步函数。

    module.exports = func => {
        return (req, res, next) => {
            func(req, res, next).catch(next);
        }
    }
    

    如果这不能解决问题,请告诉我

    【讨论】:

    • 你的解决了。非常感谢。
    • 我不必使用catch async。它立即起作用。
    • 对不起,我正在学习错误处理,你提到的 catchAsync 我不明白。当我谈到这个话题时,我感到很愚蠢。现在对我来说很有意义。再次感谢您。
    • 当然!我很高兴它修复了它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多