Node.js Course
Node.js
/
Advanced

Error Handling Middleware

Definition

A special type of Express middleware designed specifically to catch and process errors that occur anywhere in the application's synchronous or asynchronous routes.

Explain Like I'm New

A safety net under a tightrope walker. If a database query crashes, or a developer writes bad code, the app will normally crash and shut down the server. If you have an Error Middleware installed, the crash falls directly into the net. The middleware catches it, gracefully returns a 500 error to the user, and keeps the server running.

Real World Example

Writing a global error handler that checks if the error is a `ValidationError` (return 400 Bad Request to user) or an unknown database crash (hide details, log to Sentry, return 500 Internal Error).

Common Use Cases

  • •Global error catching
  • •Centralized logging to Datadog/Sentry
  • •Hiding stack traces from users in production

Interactive Example

// 1. A simulated crashing route
/*
app.get('/profile', async (req, res, next) => {
  try {
    // Something goes horribly wrong...
    throw new Error("Database connection lost!");
  } catch (error) {
    // Pass the error to the global handler
    next(error);
  }
});
*/

// 2. THE ERROR MIDDLEWARE (Must have 4 arguments!)
// This MUST be the very last app.use() in your file!
const globalErrorHandler = (err, req, res, next) => {
  console.error("[CRITICAL LOGGER]:", err.message);
  
  // Determine the type of error and respond safely
  if (err.name === 'ValidationError') {
    // res.status(400).json({ error: err.message });
  } else {
    // Hide internal crashes from the user
    // res.status(500).json({ error: "Something went wrong on our end!" });
  }
};

console.log("Express error handlers act as a centralized 'catch' block for your entire application.");

Interview Questions

basic

  • How does Express know a middleware is an Error Handler and not a normal middleware?

intermediate

  • How do you send an error from a route directly into the Error Middleware?

Flash Cards

Question

How does Express know?

Click to reveal answer
Answer

By the number of arguments! Normal middleware has 3 arguments `(req, res, next)`. Error middleware MUST have exactly 4 arguments: `(err, req, res, next)`.

Question

How do you send an error to it?

Click to reveal answer
Answer

You pass the error object directly into the next function: `next(new Error('Crash'))`. Express instantly skips all other routes and jumps straight to the Error Middleware.