Error Handling कैसे करें
Express में चार arguments वाला special error-handling middleware है जो app में कहीं से भी problems catch करता है।
In this page:
Syntax
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
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. #}
आम गलतियां
- routes से पहले error handler register करना
- यह भूल जाना कि async errors को next(err) चाहिए
- 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: