将错误消息从猫鼬验证转换为用户友好的消息

Posted

技术标签:

【中文标题】将错误消息从猫鼬验证转换为用户友好的消息【英文标题】:converting error messages from mongoose validation to user friendly messages 【发布时间】:2020-11-25 09:41:58 【问题描述】:

您好,我是一个尝试学习节点的初学者 我正在尝试验证用户在注册页面中输入的数据 这是我的猫鼬模式

const schema = mongoose.Schema(     

    fname:type:String,
        required:[true,"enter a first name"], 
    lname:type:String,
        required:[true,"enter a last name "],
    email:type:String,
        required:[true,"email is required"],
        unique:true,
        trim:true,
        lowercase:true,
    validate(value)
        if(!validator.isEmail(value))
            throw new Error("Email is invalid");
        

    
    , 
    pass:type:String,required:[true,"please enter a passkey"],minlength:[8,"enter atleast 8 characters"] 

); 

如您所见,我正在尝试验证某些字段并检查错误

usersave.save((err,doc)=>
    if(err)
        console.log(err);
        res.render("register",err:err
    
    elseconsole.log(doc);res.send("success")
);

如果用户在注册表单中输入错误数据,我会在控制台中收到以下错误消息:-

Error: users validation failed: fname: enter a first name, lname: enter a last name , pass: please enter a passkey, email: Error, expected `email` to be unique. Value: `ar@gmail.com`
    at ValidationError.inspect (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\error\validation.js:47:26)
    at formatValue (internal/util/inspect.js:718:31)
    at inspect (internal/util/inspect.js:287:10)
    at formatWithOptions (internal/util/inspect.js:1910:40)
    at Object.Console.<computed> (internal/console/constructor.js:299:10)
    at Object.log (internal/console/constructor.js:309:61)
    at D:\.UC\eb Development\react-practice\authentication\index.js:75:21
    at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\model.js:4824:16
    at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\helpers\promiseOrCallback.js:16:11
    at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\model.js:4847:21
    at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\model.js:494:16
    at D:\.UC\eb Development\react-practice\authentication\node_modules\kareem\index.js:246:48
    at next (D:\.UC\eb Development\react-practice\authentication\node_modules\kareem\index.js:167:27)
    at next (D:\.UC\eb Development\react-practice\authentication\node_modules\kareem\index.js:169:9)
    at Kareem.execPost (D:\.UC\eb Development\react-practice\authentication\node_modules\kareem\index.js:217:3)
    at _handleWrapError (D:\.UC\eb Development\react-practice\authentication\node_modules\kareem\index.js:245:21) 
  errors: 
    fname: ValidatorError: enter a first name
        at validate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1217:13)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1200:7
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1145:14)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\document.js:2392:18
        at processTicksAndRejections (internal/process/task_queues.js:79:11) 
      properties: [Object],
      kind: 'required',
      path: 'fname',
      value: '',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    ,
    lname: ValidatorError: enter a last name
        at validate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1217:13)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1200:7
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1145:14)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\document.js:2392:18
        at processTicksAndRejections (internal/process/task_queues.js:79:11) 
      properties: [Object],
      kind: 'required',
      path: 'lname',
      value: '',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    ,
    pass: ValidatorError: please enter a passkey
        at validate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1217:13)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1200:7
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1145:14)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\document.js:2392:18
        at processTicksAndRejections (internal/process/task_queues.js:79:11) 
      properties: [Object],
      kind: 'required',
      path: 'pass',
      value: '',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    ,
    email: ValidatorError: Error, expected `email` to be unique. Value: `ar@gmail.com`
        at validate (D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1217:13)
        at D:\.UC\eb Development\react-practice\authentication\node_modules\mongoose\lib\schematype.js:1192:24
        at processTicksAndRejections (internal/process/task_queues.js:97:5) 
      properties: [Object],
      kind: 'unique',
      path: 'email',
      value: 'ar@gmail.com',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    
  ,
  _message: 'users validation failed'

我希望能够在注册页面中通知用户他们做错了什么 我收到错误消息并将错误对象传递到注册页面以重新渲染 这次显示错误

当我将错误对象传递给 register.ejs 时,它包含以下信息

ValidationError: fname: enter a first name, lname: enter a last name , pass: please enter a passkey, email: Error, expected `email` to be unique. Value: `ar@gmail.com`

我想在注册页面中只显示错误消息,我该如何从上述信息中做到这一点? 或者有没有其他方法可以在前端显示错误?

【问题讨论】:

最好在模型模式中设置“required: true”,然后在路由器中管理验证和消息传递。请参阅下面的答案。 【参考方案1】:

一种方法是通过npm express-validator你可以阅读它here

然后将其包含在您的路由器文件中,然后通过路由器中间件进行验证 像这样:

const  check, validationResult  = require('express-validator');

router.post(
  '/',
  [
    //account details validation
    check('fname', 'Enter a First Name')
      .not()
      .isEmpty(),
    check('lname', 'Enter a Last name')
      .not()
      .isEmpty()
  check('email', 'type is required')
      .not()
      .isEmpty(),
  ],
  async (req, res) => 
    try 
     const errors = validationResult(req);
   //Check if there are errors 
    if (!errors.isEmpty()) 
    //If so Send response status with the error message
      return res
        .status(500)
        .json( status: false, data: errors.array()[0].msg );
    
//... Rest of code is here ... 
     catch (error) 
      res.status(500).json( status: false, error: error.message );
    
  
);

我建议您阅读有关快速路由和将响应状态传递到前端的信息

必须说响应取决于您的实施,您也可以使用

res.send(errors.array()[0].msg)

只发送消息本身。 在上面的代码中,我使用 json obj 和响应状态来区分错误类型。 这完全取决于您的决定,希望这是有道理的。 祝你好运

【讨论】:

以上是关于将错误消息从猫鼬验证转换为用户友好的消息的主要内容,如果未能解决你的问题,请参考以下文章

为最终用户处理 Flutter 上的 Firebase 身份验证错误

使 C# 中捕获的 Mysql 错误对用户友好

打字稿模型添加猫鼬身份验证

在角度视图中注入猫鼬模型验证

如何在猫鼬中返回自定义错误?

Laravel - “其他”占位符不接受验证消息中的友好名称