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

Errors को Handle करना

Validation errors, duplicate keys, और connection failures explicitly handle करें ताकि आपकी app sensibly respond करे।

In this page:

  1. Error Handling
Syntax
javascript
try {
  await Model.create(document);
} catch (err) {
  // handle err.name, err.message
}

Error Handling

Database calls को try/catch में wrap करें। Mongoose ValidationError field problems list करता है, duplicate keys code 11000 के साथ एक error throw करते हैं, और invalid ids CastError cause करते हैं।

Outages के लिए connection events सुनें, और 400, 404, और 409 जैसे clear HTTP status codes return करें।

Note: duplicate key conflicts के लिए err.code === 11000 check करें।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. unhandled rejections को process crash करने देना
  2. clients को raw errors return करना
  3. connection error events ignore करना
चैप्टर सारांश
  • Database calls के चारों ओर try/catch
  • ValidationError, CastError, code 11000 जैसी errors आती हैं
  • Errors को HTTP statuses में map करें
  • 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.