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

Error handling

Express has special error-handling middleware with four arguments that catches problems from anywhere in the app.

In this page:

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

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
  1. Registering the error handler before routes
  2. Forgetting async errors need next(err)
  3. 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:

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.