【问题标题】:How to customize Mongoose/MongoDB error sent from Express如何自定义从 Express 发送的 Mongoose/MongoDB 错误
【发布时间】:2021-03-22 22:43:42
【问题描述】:

当用户尝试创建包含“密码”一词的密码时,我将错误消息发送回我的 iOS 客户端。

我想向用户显示一条简单的消息,而不必在客户端上对字符串等进行切片,所以我不想发送部分'用户验证失败:密码:'仅'password 不能包含单词 password'。

如何在 Node/Express 中自定义此消息?它是 Mongoose 还是 MongoDB 实现?

谢谢!

// Mongoose password model.
password : {
     type: String,
     required: [true, "password is required"],
     validate(value) {
         if (value.length < 6) {
             throw new Error(`password must be longer than 6 characters`)
            }
         if (value.toLowerCase().includes(`password`)) {
             throw new Error(`password cannot contain the word ${value}`)
            }
        },
     trim: true,
     minLength: [6, "password cannot be shorter than 8 characters"],
     maxlength: [80, "name cannot be longer than 30 characters"]
    },

// Router error response
catch(err) {
        console.log(err.message)     
        res.status(500).send({error: err.message}) 
    }
-> User validation failed: password: password cannot contain the word password

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    在 Express 中发送错误消息之前,您始终可以自定义错误消息:

    catch(err) {
      console.log(err.message) 
      // Add Message Customization Here:
      const message = err.message.replace("User validation failed: password:", "");    
      res.status(500).send({error: message}) 
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-24
      • 2020-03-17
      • 2017-11-19
      • 2021-03-17
      • 2019-10-19
      • 2019-07-12
      • 1970-01-01
      • 2016-12-21
      • 2017-09-10
      相关资源
      最近更新 更多