【发布时间】: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