Javascript 在Express中使用自定义错误中间件时未定义next
我正在尝试使用express中的next()将错误通过以下路径传递给自定义中间件:Javascript 在Express中使用自定义错误中间件时未定义next,javascript,node.js,express,Javascript,Node.js,Express,我正在尝试使用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"
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);
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().
在所有其他app.use()之后,我在最后一个文件中添加了这个中间件。
但我一直收到如下参考错误:
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);
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块,但它似乎抛出了错误。
我尝试将错误处理程序的定义添加到顶部,但仍然显示相同的错误。更改
app.post("/api/persons", (req, res) => { // next is missing here
// ..///
});
到
由于承诺会自动捕获同步错误和被拒绝的承诺,因此您可以简单地提供next作为最终的捕获处理程序,Express将捕获错误,因为捕获处理程序将错误作为第一个参数
读-
对于路由处理程序和中间件调用的异步函数返回的错误,必须将它们传递给next()函数,Express将在其中捕获并处理它们
谢谢!我完全忘了在params中添加它。@AbhishekGhadge很高兴它有帮助,干杯:)