处理 Express 框架中的错误的问题

Problem with handling errors in Express framework

我目前正在从事 node.js + express + mongoDB 项目。我正在尝试处理无法从数据库接收数据时发生的错误。我通过在控制台中终止 mongod 进程并在 Postman 中调用 .get 来模拟这一点。可悲的是,我没有在 Postman 中得到错误,而是在控制台中得到了 Unhandled Promise Rejection。我阅读了很多关于错误处理的帖子,并根据这个指南实现了它: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(错误)被放在最后app.use

您的代码中有一个小错误。不应更改错误处理函数中 reqres 参数的顺序。

// Error.js
module.exports = function (err, req, res, next) {
  res.status(500).send(`500 Error`);
};