提问者:小点点

如何自定义从Express发送的Mongoose/MongoDB错误


当一个用户试图创建一个包含“password”的密码时,我正在向我的iOS客户端发送一条错误消息。

我想向用户显示一个简单的消息,而不需要在客户端上分割字符串等,所以我不想发送“用户验证失败:密码:”只有“密码不能包含单词密码”。

如何在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

共1个答案

匿名用户

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

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}) 
}