如何在Express接口中捕获Mongoose ValidationError?
解决Mongoose ValidationError导致服务器崩溃的问题
问题根源
你的代码中ppty.save()是异步Promise操作,但未添加await关键字,导致它抛出的错误无法被外层try/catch捕获,进而引发服务器崩溃。同时catch块处理完验证错误后未终止后续代码,会触发重复响应的问题。
修复后的代码
const post_property = async (req, res) => { try { const ppty = new Properties(req.body); // 必须添加await,确保异步操作的错误能被try/catch捕获 await ppty.save(); res.status(201).json({status: true, msg: "Property created", property: ppty}); } catch (error) { if (error instanceof mongoose.Error.ValidationError) { // 处理必填项缺失的验证错误,返回400状态码 return res.status(400).json({ status: false, msg: "必填字段缺失或格式不符合要求", // 可选:提取具体字段的错误信息,方便前端定位问题 errors: Object.fromEntries( Object.entries(error.errors).map(([field, err]) => [field, err.message]) ) }); } // 处理其他服务器内部错误 return res.status(500).json({status: false, msg: error.message}); } }
核心修复说明
- 添加
await关键字:save()是异步操作,必须用await等待其执行完成,这样抛出的错误才能被try/catch捕获。 - 添加
return终止响应:每个res.json()前加return,避免同一请求多次发送响应,防止出现Cannot set headers after they are sent to the client错误。
你的Schema定义
const PropertiesSchema = new mongoose.Schema( { name: { type: String, required: true }, address: { street: { type: String, required: true }, number_or_apt: { type: String, required: true }, city: { type: String, required: true }, state_province: { type: String, required: true }, zip_code: { type: String, required: true }, country: { type: String, required: true }, latitude: { type: String, required: true }, longitude: { type: String, required: true }, }, property_images: [ String ], } ); const Properties = mongoose.model('properties', PropertiesSchema);
内容的提问来源于stack exchange,提问作者Mauricio
相关产品推荐
相关产品推荐

