← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 6 of 7

Error handling

Handle validation errors, duplicate keys and connection failures explicitly so your app responds sensibly.

In this page:

  1. Error handling
Syntax
javascript
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

javascript
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
  1. Letting unhandled rejections crash the process
  2. Returning raw errors to clients
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.