【问题标题】:How can I handle runtime errors on Express app?如何处理 Express 应用程序上的运行时错误?
【发布时间】:2017-04-19 15:37:29
【问题描述】:

我是 express + node.js 的新手,所以我使用 mongoose 编写了一个 rest api。处理运行时错误(如数据库错误等)的最佳方法是什么?

我在 express 文档中读到,您可以使用中间件 function(err, res, req, next) 来处理此错误,并且您可以仅调用 next(err) 来调用此函数。没关系,所以想象一下,你有一个 User moongose 模型,并在控制器中编写了这个函数:

const find = (email, password) => {
  User.find({ email: email }, (err, doc) => {
    if (err) {
      // handle error
    }
    return doc;
  });
};

然后,您在另一个文件中有一个路由处理程序:

router.get('/users', (req, res) => {
    userController.find(req.body.email);
});

所以,此时,您可以处理在模型中写入throw(err) 并在控制器中使用try/catch 然后调用next(err) 的mongo 错误,对吧?但我读过在 JavaScript 中使用 try/catch 并不是一个好习惯,因为它会创建一个新的执行上下文等。

在 Express 中处理此错误的最佳方法是什么?

【问题讨论】:

  • 使用try/catch 语句没有错。就个人而言,我会采用为此类操作创建Promises 的方法,以便我可以使用.catch 进行错误处理。

标签: node.js express


【解决方案1】:

我会建议你使用 Promise。它不仅使您的代码更清晰,而且错误处理也更容易。如需参考,您可以访问thisthis

如果您使用的是 mongoose,您可以插入自己的 Promise 库。

const mongoose = require('mongoose');
mongoose.connect(uri);

// plug in the promise library:
mongoose.Promise = global.Promise;

mongoose.connection.on('error', (err) => {
  console.error(`Mongoose connection error: ${err}`)
  process.exit(1)
})

并像下面这样使用它:

在控制器中:

const find = (email) => {
  var userQuery = User.find({ email: email });
  return userQuery.exec();
};

在路由器中:

router.get('/users', (req, res) => {
    userController.find(req.body.email).then(function(docs){
      // Send your response
    }).then(null, function(err){
      //Handle Error
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 2012-10-30
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2019-06-14
    相关资源
    最近更新 更多