首页 > 解决方案 > 如何自定义从 Express 发送的 Mongoose/MongoDB 错误

问题描述

当用户尝试创建包含“密码”一词的密码时,我正在向我的 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

标签: node.jsmongodbexpressmongoose

解决方案


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

推荐阅读