抛出Mongoose pre中间件的自定义错误,并使用蓝鸟承诺

我用蓝鸟承诺使用mongoose。 我正在尝试在validation前中间件中抛出一个自定义错误,并使其捕捉到Bluebird catch。

这是我的validation方法

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 

有没有办法让我的自定义错误是什么交付给渔获? 我想这样我可以检查错误types,并让控制器在响应中回应相应的消息。

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);