← Back to Node.js Course | Chapter 7: Express.js Basics | Lesson 7 of 7

Error Handling कैसे करें

Express में चार arguments वाला special error-handling middleware है जो app में कहीं से भी problems catch करता है।

In this page:

  1. Error Handling
Syntax
javascript
app.use((err, req, res, next) => {
  res.status(statusCode).json({ error: err.message });
});

Error Handling

एक error handler का signature (err, req, res, next) है और routes के बाद register होता है।

next(err) call करना या sync code में throw करना control को इसकी ओर route करता है। Express 4 में, async errors को next को pass करना या wrap करना ज़रूरी है।

एक safe message return करें और details log करें।

Note: Production में clients को stack traces न भेजें।

उदाहरण: Error handling

bash
app.get("/boom", (req, res, next) => next(new Error("something broke")));
app.use((req, res) => res.status(404).json({ error: "Not found" }));
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).json({ error: "Internal Server Error" });
});

⚠️ 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. routes से पहले error handler register करना
  2. यह भूल जाना कि async errors को next(err) चाहिए
  3. stack traces leak करना
चैप्टर सारांश
  • Error middleware के चार arguments हैं
  • इसे आखिर में register करें
  • next(err) errors forward करता है
  • Clients से internals hide करें
🔒

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.