Error Handling: Graceful Failure

Error Handling: Graceful Failure in JavaScript: When your code crashes (e.g., the database is down), you don't want the user to see a messy, scary error…

Concept Explanation

When your code crashes (e.g., the database is down), you don't want the user to see a messy, scary error message. You want to "Catch" the error and send back a polite 500 Internal Server Error message.


Syntax or Core Structure

Express has a special type of middleware with 4 arguments instead of 3.

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    message: "Something went wrong on our end!",
    error: err.message
  });
});

Real World Example

The Async Trap: In Express 4, an error thrown inside an async route is not caught by your error middleware — the promise rejects silently and the request hangs. You must catch it and pass it on with next(err):

app.get("/user", async (req, res, next) => {
  try {
    const user = await db.find(req.query.id);
    res.json(user);
  } catch (err) {
    next(err); // hand off to the error middleware
  }
});

Common Mistakes

  • Leaking Stack Traces: Never send err.stack to the client in production — it reveals your file paths and logic to attackers.
  • Wrong Argument Count: Error middleware must have all four params (err, req, res, next). Drop one and Express treats it as normal middleware.
  • Forgetting next(err): In async routes, an uncaught rejection never reaches your handler.

Best Practices

  • One Central Handler: Keep a single error middleware at the very bottom of the stack.
  • Log Server-Side, Hide Client-Side: Log the full error for yourself; send a generic message to the user.
  • Custom Error Classes: Throw new AppError("Not found", 404) so your handler can read a proper status code.

Practice Exercises

  1. The Error Trigger: Write a route that deliberately throws an error (throw new Error("Boom!")) and ensure your error middleware catches it.
  2. The 404 Catcher: Write a middleware at the very bottom of your app that catches every request that didn't match a route and sends back a custom "Page Not Found" JSON.
  3. Async Errors: Research why try/catch is required inside async routes in Express 4, and how Express 5 makes this easier.