【问题标题】:next is not defined while using custom error middleware in Express在 Express 中使用自定义错误中间件时未定义 next
【发布时间】:2021-06-30 23:41:14
【问题描述】:

我正在尝试在 express 中使用 next() 将错误传递给以下路由中的自定义中间件:

app.post("/api/persons", (req, res) => {
  const findPerson = Person.findOne({ name: req.body.name });
  if (findPerson.length) {
    res.status(404).json({ error: "Name already exists" });
  } else if (req.body && req.body.name && req.body.number) {
    const person = new Person({
      name: req.body.name,
      number: req.body.number,
    });
    person
      .save()
      .then((savedPerson) => {
        console.log("saved successfully.");
        res.json(savedPerson).end();
      })
      .catch((err) => next(err));
    app.use(morgan("tiny"));
  } else {
    res.status(404).json({ error: "Name or number missing" });
  }
});

我已经定义了中间件函数如下:

const errorHandler = (error, request, response, next) => {
  console.error(error.message);

  if (error.name === "CastError") {
    return response.status(400).send({ error: "malformatted id" });
  }

  next(error);
};
app.use(errorHandler);

在所有其他 app.use() 之后,我将此中间件添加到文件的最后。 但我不断收到如下参考错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

即使我清楚地使用了 catch 块,它似乎也会抛出错误。 我尝试将错误处理程序的定义添加到顶部,但它仍然显示相同的错误。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    改变

    app.post("/api/persons", (req, res) => { // next is missing here
     // ..///
    });
    

    app.post("/api/persons", (req, res, next) => { // add next  here
     // ../// next(err); // call next with error now
    });
    

    由于 Promise 自动捕获同步错误和被拒绝的 Promise,您可以简单地提供 next 作为最终的 catch 处理程序,Express 将捕获错误,因为 catch 处理程序将错误作为第一个参数。

    阅读 - https://expressjs.com/en/guide/error-handling.html

    对于由路由处理程序和中间件调用的异步函数返回的错误,您必须将它们传递给 next() 函数,Express 将在其中捕获并处理它们。

    function errorHandler (err, req, res, next) {
      if (res.headersSent) {
        return next(err)
      }
      res.status(500)
      res.render('error', { error: err })
    }
    

    【讨论】:

    • 非常感谢!我完全忘了在参数中添加它。
    • @AbhishekGhadge 很高兴它有帮助,干杯 :)
    猜你喜欢
    • 2020-07-13
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2018-07-02
    • 2020-04-09
    • 2021-12-04
    相关资源
    最近更新 更多