自定义(用户友好)ValidatorError消息
我真的是新来的mongoose,所以我想知道是否有一些方法来设置custom error message
而不是默认的一个像Validator "required" failed for path password
。
我想设置像Password is required.
这更方便用户使用。
我写了一些自定义validation器,并设置type
属性与这个用户友好的错误消息,但我不知道type
是错误消息的正确的占位符。 还有没有办法设置定制的消息,如min, max, required, enum...
等预定义的validationmin, max, required, enum...
一个解决scheme是检查每次抛出错误的type
属性并手动分配错误消息,但认为这是validation器的工作:
save model if error check error type (eg. "required") assign fancy error message (eg. "Password is required.")
这显然不是理想的解决scheme。
我看了expression式和节点validation器,但仍想使用mongoosevalidationfunction。
我通常使用一个辅助函数来处理这些事情。 只是嘲笑这一个比我使用的一个更普遍。 这个人将采取所有的“默认”validation(要求,最小值,最大值等),并使他们的消息更漂亮一些(根据下面的messages
对象),并只提取消息,你通过validation器为自定义validation。
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); }
它可以像这样使用(express router example):
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); } }
之前:
{ 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' } } }
后:
[ 'username is required.', 'state not an allowed value.', 'custom validator here', 'age below minimum.' ]
编辑 :快照,只是意识到这是一个CoffeeScript的问题。 不是一个CoffeeScript的家伙,我真的不想在CS重写这个。 你总是可以只需要它作为一个js
文件到你的CS?
如果您需要获取第一个错误消息,请参阅以下示例:
var firstError = err.errors[Object.keys(err.errors)[0]]; return res.status(500).send(firstError.message);
问候,Nicholls