【问题标题】:mongodb error handling whlle using exec使用 exec 的 mongodb 错误处理
【发布时间】:2017-04-17 21:45:31
【问题描述】:

我有 ExpressJS、NodeJs、Mongoose 应用程序。 我已经编写了如下所示的 mongodb 代码,并且运行良好。

module.exports.getStudentid = function(id, callback) {

    Student
        .find({ _id: id })
        .populate('marks')       
        .exec(callback);
}

但就 NodeJS 中的错误处理而言,它是一个好的代码吗?它会将错误传递给下一层吗?如何改进上述代码以使用正确的错误处理?

【问题讨论】:

标签: node.js express mongoose error-handling


【解决方案1】:

应该定义你的回调函数来支持你的错误。您的回调应如下所示:

function (err, student) {
  if (err) {
     // handle error err, will have your error
     return;
  } 
  return student;
}

你如何将它传递到下一层将取决于你在注释行中所做的事情......我的建议,将其更改为使用承诺:

const Q                 = require('q');
module.exports.getStudentById = function getById(id) {
    let deferred = Q.defer();
    Student
        .find({ _id: id })
        .populate('marks')       
        .exec(function doAfterExec(err, student){ 
          if (err) {
            deferred.reject(err);
          }
          deferred.resolve(student);
    });
 return deferred.promise;
}

然后调用它,假设你之前的模块被称为StudentIO

const io = require("StudentIO");
io.getStudentById(id)
.then(function doSuccess(result) {
   console.log("yeeei!!!", result);
})
.fail(function doError(err) {
   console.log("buuu", err);
});

如果您使用新的=> 语法,这可能会更清晰,但我没有包含它,因为不确定您是否正在使用它。所以我使用了常规的函数符号。

希望这可以带来一些启发。看看 Q 和 Promise……它可以很容易地摆脱回调地狱的场景。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 2020-09-14
    • 2021-06-05
    • 2022-08-04
    • 2017-05-29
    • 2021-01-05
    • 1970-01-01
    • 2017-10-18
    • 2018-04-30
    相关资源
    最近更新 更多