处理猫鼬验证错误–在何处以及如何进行? [英] Handling Mongoose validation errors – where and how?
问题描述
我正试图决定如何处理猫鼬中的验证错误.
I'm trying to decide how I want to handle validation errors in Mongoose.
我已经使用 node-validator 定义了自己的验证规则,例如:
I have defined my own validation rules using node-validator, for example:
UserSchema.path('username')
.validate(function (username) {
return validator.check(username).notEmpty()
}, 'Username cannot be blank')
这将产生如下错误:
username:
{ message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank' },
使用猫鼬验证器
但是,node-validator提供了自己的错误消息.如果我使用 mongoose-validator 节点模块将node-validator直接插入到我的模式中,那么我可以直接使用以下错误消息:
Using mongoose-validator
However, node-validator provides its own error messages. If I use the mongoose-validator Node module to plug node-validator directly into my schema, then I can use these error messages directly instead:
var UserSchema = new Schema({
name: { type: String, validate: [validate('notEmpty')] }
});
这将生成如下错误消息:
Which will generate an error message that looks like:
name:
{ message: 'Validator "String is empty" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'String is empty' } }
我也可以在此处提供自定义错误消息:
I can also provide a custom error message here too:
var UserSchema = new Schema({
name: { type: String, validate: [validate({message: 'Name cannot be blank' }, 'notEmpty')] }
});
猫鼬required
标志
猫鼬允许您根据需要定义一个字段:
Mongoose required
flag
Mongoose lets you define a field as required:
var UserSchema = new Schema({
name: { type: String, required: true }
});
这将生成如下错误消息:
Which will generate an error message that looks like:
name:
{ message: 'Validator "required" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'required' } }
问题
感觉这些验证器想要来使用它们的内置错误消息.例如,如上所述,我想将一个字段声明为required
,但是找不到自定义错误消息的方法. mongoose-validator模块直到最近才支持自定义消息,这使我认为它们在模型级别是反模式.
The question
It feels as if these validators want you to use their built-in error messages. For instance, I want to declare a field as required
as seen above, but I can't find a way of customising the error message. And the mongoose-validator module did not support custom messages up until very recently, which makes me think they are an anti-pattern at the model level.
实现这些验证器的最佳方法是什么?我应该让他们产生自己的错误,然后以某种方式对它们进行解释吗?
What's the best way to implement these validators? Should I let them generate their own errors and then somehow interpret them afterwards?
推荐答案
在这一点上,了解猫鼬如何处理错误似乎是合乎逻辑的.
At this point it seems logical to buy in to how mongoose handles errors.
您不希望您的模型处理错误消息.表示层(控制器?)应该依靠type
来决定要显示的最佳用户友好消息(考虑为i18n).
You would not want your models to handle error messages. The presentation layer (controllers?) should rely on the type
to decide on which is the best user-friendly message to display (i18n considered).
在某些情况下,可能会通过使用中间件进行验证.在这种情况下,传递给next()
回调的任何内容都会浮现到控制器的错误消息中.
There's also the case where validation may happen by using a middleware. In this case, the error message that will surface up to your controller is whatever you pass to the next()
callback.
因此,对于中间件,尽管没有记录,但是为了在模型之间保持一致的验证API,您应该直接使用Mongoose的Error构造函数:
So, for the case of middleware, although not documented, in order to keep a consistent validation API across your models you should directly use Mongoose's Error constructors:
var mongoose = require('mongoose');
var ValidationError = mongoose.Error.ValidationError;
var ValidatorError = mongoose.Error.ValidatorError;
schema.pre('save', function (next) {
if (/someregex/i.test(this.email)) {
var error = new ValidationError(this);
error.errors.email = new ValidatorError('email', 'Email is not valid', 'notvalid', this.email);
return next(error);
}
next();
});
这样,即使验证错误源自中间件,也可以确保您对验证错误进行一致的处理.
That way you are guaranteed a consistent validation error handling even if the validation error originates from a middleware.
为使错误消息与类型正确匹配,我将创建一个枚举,该枚举将充当所有可能类型的静态映射:
To properly match error messages to types I'd create an enum which would act as a static map for all possible types:
// my controller.js
var ValidationErrors = {
REQUIRED: 'required',
NOTVALID: 'notvalid',
/* ... */
};
app.post('/register', function(req, res){
var user = new userModel.Model(req.body);
user.save(function(err){
if (err) {
var errMessage = '';
// go through all the errors...
for (var errName in err.errors) {
switch(err.errors[errName].type) {
case ValidationErrors.REQUIRED:
errMessage = i18n('Field is required');
break;
case ValidationErrors.NOTVALID:
errMessage = i18n('Field is not valid');
break;
}
}
res.send(errMessage);
}
});
});
这篇关于处理猫鼬验证错误–在何处以及如何进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!