Error handling
Handle validation errors, duplicate keys and connection failures explicitly so your app responds sensibly.
In this page:
Syntax
try {
await Model.create(document);
} catch (err) {
// handle err.name, err.message
}
Error handling
Wrap database calls in try/catch. Mongoose ValidationError lists field problems, duplicate keys throw an error with code 11000, and invalid ids cause CastError.
Listen to connection events for outages, and return clear HTTP status codes such as 400, 404 and 409.
Note:
Check err.code === 11000 for duplicate key conflicts.
Example: Error handling
try {
await User.create({ name: "Ada", email: "[email protected]" });
} catch (err) {
if (err.code === 11000) return res.status(409).json({ error: "Email already exists" });
if (err.name === "ValidationError") return res.status(400).json({ error: err.message });
if (err.name === "CastError") return res.status(400).json({ error: "Invalid id" });
console.error(err);
res.status(500).json({ error: "Server error" });
}
mongoose.connection.on("error", (e) => console.error("Mongo error", e.message));
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Letting unhandled rejections crash the process
- Returning raw errors to clients
- Ignoring connection error events
Chapter Summary
- try/catch around database calls
- ValidationError, CastError, code 11000
- Map errors to HTTP statuses
- Listen for connection events
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: