node.js - 如何自定义从 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
解决方案
在 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})
}
推荐阅读
- amazon-web-services - AWS SNS 终端节点在 IST 晚上 9 点之后不发送短信
- arangodb - 如何以有用的格式提取 ArangoDB 嵌入式列表
- hadoop - 如何安全地将数据附加到分区的 Hive 表中?
- c - 客户端服务器程序中的多线程概念
- sql - 错误:违反外键约束,父表中不存在键(但它是??)
- php - 我可以在 Wordpress 编辑器中将 3 个最近帖子的列表动态输出到默认文本中吗?
- vue.js - 将 v-bind 与过滤器结合使用时如何保持反应性
- java - 导航控制器方向
- javascript - 使用 JS 生成多个 html 元素时,最有效的方式是什么?
- javascript - 赛普拉斯:运行所有规范,但创建一个没有运行规范的循环