javascript - 在 Express 中使用自定义错误中间件时未定义 next
问题描述
我正在尝试在 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 块,它似乎也会抛出错误。我尝试将错误处理程序的定义添加到顶部,但它仍然显示相同的错误。
解决方案
Change
app.post("/api/persons", (req, res) => { // next is missing here
// ..///
});
To
app.post("/api/persons", (req, res, next) => { // add next here
// ../// next(err); // call next with error now
});
Since promises automatically catch both synchronous errors and rejected promises, you can simply provide next as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument.
Read - https://expressjs.com/en/guide/error-handling.html
For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them.
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
推荐阅读
- javascript - Discord BOT 对命令无响应且无控制台输出 (discord.js)
- python - 将列标签添加到条形图(Python-matplotlib)
- amazon-web-services - 使用 cloudformation 部署 ec2 实例
- c - 指针和嵌套结构如何工作?
- jenkins - 如何在输入布尔参数中添加 ArrayList
- javascript - Google Drive Web API 保存和下载 pdf
- mysql - Chart JS 2.x 不在工具提示中显示多个数据,并带有来自 MySql 数据库的回调
- apache - 在 Apache (API) 的 url 中传递凭据
- javascript - 如何在 JSDoc 中查找 typedef 的类型/使用 typedef 的属性
- reactjs - React js reducer 逻辑条件