【问题标题】:Throwing custom errors from Mongoose pre middleware and using Bluebird promises从 Mongoose 预中间件中抛出自定义错误并使用 Bluebird 承诺
【发布时间】:2015-04-15 02:42:45
【问题描述】:

我正在使用带有 Bluebird 承诺的 Mongoose。我试图在 validate pre 中间件中抛出一个自定义错误,并让它可以被 Bluebird catch 捕获。

这是我的预验证方法

schema.pre('validate', function(next) {
  var self = this;

  if (self.isNew) {
    if (self.isModified('email')) {
      // Check if email address on new User is a duplicate
      checkForDuplicate(self, next);
    }
  }

});

function checkForDuplicate(model, cb) {
  User.where({email: model.email}).count(function(err, count) {
    if (err) return cb(err);
    // If one is found, throw an error
    if (count > 0) {
      return cb(new User.DuplicateEmailError());
    }
    cb();
  });
}

User.DuplicateEmailError = function () {
  this.name = 'DuplicateEmailError';
  this.message = 'The email used on the new user already exists for another user';
}
User.DuplicateEmailError.prototype = Error.prototype;

我在我的控制器中使用以下内容调用保存

User.massAssign(request.payload).saveAsync()
  .then(function(user) {
    debugger;
    reply(user);
  })
  .catch(function(err) {
    debugger;
    reply(err);
  });

这导致.catch() 出现如下错误:

err: OperationalError
  cause: Error
  isOperational: true
  message: "The email used on the new user already exists for another user"
  name: "DuplicateEmailError"
  stack: undefined
  __proto__: OperationalError

我有没有办法让自定义错误成为传递给捕获的内容?我想要 tis,以便我可以检查错误类型,并让控制器在响应中返回适当的消息。

【问题讨论】:

    标签: node.js mongoose promise bluebird


    【解决方案1】:

    User.DuplicateEmailError.prototype = Error.prototype;

    错了,应该是

    User.DuplicateEmailError.prototype = Object.create(Error.prototype);
    User.DuplicateEmailError.prototype.constructor = User.DuplicateEmailError;
    

    或者更好的使用

       var util = require("util");
    
       ...
    
       util.inherits(User.DuplicateEmailError, Error);
    

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 1970-01-01
      • 2016-07-27
      • 2014-05-06
      • 1970-01-01
      • 2018-10-29
      • 2022-01-10
      • 2020-08-29
      • 2016-02-26
      相关资源
      最近更新 更多