自定义(用户友好)ValidatorError消息

Man*_*Box 11 error-handling mongoose mongodb node.js express

我对mongoose很新,所以我想知道是否有某种方法来设置custom error message而不是默认的方式Validator "required" failed for path password.

我想设置一些Password is required.更加用户友好的东西.

我写了一些自定义验证器并type使用此用户友好的错误消息设置属性,但我不确定type是错误消息的正确占位符.也没有办法在预定义的验证器上设置自定义消息min, max, required, enum...

一种解决方案是检查每次type抛出错误的属性并手动分配错误消息,但认为这是验证者的工作:

save model
    if error
        check error type (eg. "required")
        assign fancy error message (eg. "Password is required.")
Run Code Online (Sandbox Code Playgroud)

这显然不是理想的解决方案.

我查看了express-formnode-validator,但仍想使用mongoose验证功能.

cla*_*rkf 16

我通常使用辅助函数来做这些事情.只是嘲笑这个比我使用的更一般.这个人将采用所有"默认"验证器(必需,最小,最大等)并使他们的消息更漂亮(根据messages下面的对象),并提取您在验证器中传递的消息以进行自定义验证.

function errorHelper(err, cb) {
    //If it isn't a mongoose-validation error, just throw it.
    if (err.name !== 'ValidationError') return cb(err);
    var messages = {
        'required': "%s is required.",
        'min': "%s below minimum.",
        'max': "%s above maximum.",
        'enum': "%s not an allowed value."
    };

    //A validationerror can contain more than one error.
    var errors = [];

    //Loop over the errors object of the Validation Error
    Object.keys(err.errors).forEach(function (field) {
        var eObj = err.errors[field];

        //If we don't have a message for `type`, just push the error through
        if (!messages.hasOwnProperty(eObj.type)) errors.push(eObj.type);

        //Otherwise, use util.format to format the message, and passing the path
        else errors.push(require('util').format(messages[eObj.type], eObj.path));
    });

    return cb(errors);
}
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用(快速路由器示例):

function (req, res, next) {
    //generate `user` here
    user.save(function (err) {
        //If we have an error, call the helper, return, and pass it `next`
        //to pass the "user-friendly" errors to
        if (err) return errorHelper(err, next);
    }
}
Run Code Online (Sandbox Code Playgroud)

之前:

{ message: 'Validation failed',
  name: 'ValidationError',
  errors: 
   { username: 
      { message: 'Validator "required" failed for path username',
        name: 'ValidatorError',
        path: 'username',
        type: 'required' },
     state: 
      { message: 'Validator "enum" failed for path state',
        name: 'ValidatorError',
        path: 'state',
        type: 'enum' },
     email: 
      { message: 'Validator "custom validator here" failed for path email',
        name: 'ValidatorError',
        path: 'email',
        type: 'custom validator here' },
     age: 
      { message: 'Validator "min" failed for path age',
        name: 'ValidatorError',
        path: 'age',
        type: 'min' } } }
Run Code Online (Sandbox Code Playgroud)

后:

[ 'username is required.',
  'state not an allowed value.',
  'custom validator here',
  'age below minimum.' ]
Run Code Online (Sandbox Code Playgroud)

编辑:Snap,刚才意识到这是一个CoffeeScript问题.不是CoffeeScript的人,我真的不想在CS中重写它.您可以随时将它作为js文件存入您的CS吗?