Error Handlers & Application Logging

🦁 Express.jsLesson 12Advanced

Express features a built-in default error handler that takes care of errors in the router middleware stack. Custom error handlers are defined as special middlewares containing 4 arguments.

1 Custom 4-parameter Error Middleware

To register an error-handling middleware, place it at the very bottom of your application stack after all other routes and middleware definitions:

JavaScript — error_handler.js
// 4 argument signature: (err, req, res, next)
app.use((err, req, res, next) => {
  console.error("Global Error Handler caught:", err.stack);
  
  res.status(err.status || 500).json({
    error: true,
    message: err.message || "Internal Server Error"
  });
});
2 Integrating morgan HTTP logging

Morgan logs server activity in detail. Install it with npm install morgan:

JavaScript — HTTP Logs configuration
const morgan = require("morgan");

// Write all requests to combined log format
app.use(morgan("combined"));
3 Code Challenge
Challenge: Write a route that intentionally throws a custom JavaScript error (e.g. new Error("Resource missing")). Test that your custom global error middleware catches it and returns a 500 status payload.