Error handling
Express has special error-handling middleware with four arguments that catches problems from anywhere in the app.
In this page:
Syntax
app.use((err, req, res, next) => {
res.status(statusCode).json({ error: err.message });
});
Error handling
An error handler has the signature (err, req, res, next) and is registered after routes.
Calling next(err) or throwing in sync code routes control to it. In Express 4, async errors need to be passed to next or wrapped.
Return a safe message and log details.
Note:
Do not send stack traces to clients in production.
Example: 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. #}
Common Mistakes
- Registering the error handler before routes
- Forgetting async errors need next(err)
- Leaking stack traces
Chapter Summary
- Error middleware has four arguments
- Register it last
- next(err) forwards errors
- Hide internals from clients
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: