【发布时间】:2021-05-21 07:09:35
【问题描述】:
我目前正在处理 node.js + express + mongoDB 项目。我正在尝试处理无法从数据库接收数据时发生的错误。我通过在控制台中终止 mongod 进程并在 Postman 中调用 .get 来模拟这一点。可悲的是,我只在控制台中收到 Unhandled Promise Rejection 而不是在 Postman 中出现错误。我阅读了很多关于错误处理的帖子并根据本指南实现了它:https://expressjs.com/en/guide/error-handling.html。如果我能解决这个问题,我将不胜感激。
代码:
打印所有课程:
router.get("/", async (req, res, next) => {
try {
const courses = await Course.find().sort("dishName");
res.send(courses);
} catch (ex) {
next(ex);
}
});
error.js:
module.exports = function (err, res, req, next) {
res.status(500).send(`500 Error`);
};
index.js
const error = require(`./middleware/error`);
app.use(error);
app.use(error) 被放置为最后一个 app.use
【问题讨论】:
标签: node.js express error-handling