Well-structured backends separate concerns: routers define URLs, controllers translate HTTP to application calls, services own data access, and middleware handles cross-cutting behavior (validation, 404, errors). Study these patterns to keep files small, testable, and aligned with REST conventions.

How to handle errors globally — Intermediate

Use a centralized errorHandler middleware to format errors and set status codes.
Learn: Express recognizes error-handling middleware by its four arguments `(err, req, res, next)`. Log the error, map known status codes, and avoid leaking stack traces in production.

Supplementary examples

Central error handler

function errorHandler(err, req, res, next) {
  const status = err.status || err.statusCode || 500;
  req.log?.error(err);
  res.status(status).json({
    error: err.message || "Internal Server Error",
  });
}

app.use(errorHandler); // after notFound

Course example

const checkForAbbreviationLength = (req, res, next) => {
const abbreviation = req.params.abbreviation;
if (abbreviation.length !== 2) {
next("State abbreviation is invalid.");
} else {
next();
}
};

Additional references & examples

← All Error handling · Server Architecture / Routes