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.

Error handling

Matches the lesson Error handling: notFound for unknown URLs and a global errorHandler.

2 topic(s) on this page.

How to handle unknown routes — Basic

Register a notFound middleware after all routes to return a consistent 404 response.
Learn: If no route matched, Express falls through to the next middleware. Register notFound after all routers so clients get a consistent JSON 404 instead of a generic HTML page.

Supplementary examples

notFound middleware

function notFound(req, res, next) {
  res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
}

// in app.js, after all routes:
app.use(notFound);

Course example

const express = require("express");
const cors = require("cors");
const app = express();
const corsEnabledRouter = require("./cors-enabled/cors-enabled.router");
const corsNotEnabledRouter = require("./cors-not-enabled/cors-not-enabled.router");
const notFound = require("./errors/notFound");
const errorHandler = require("./errors/errorHandler");
app.use(cors());
app.use(express.json());
app.use("/cors-enabled", corsEnabledRouter);
app.use("/cors-not-enabled", corsNotEnabledRouter);
app.use(notFound);
app.use(errorHandler);
module.exports = app;

Additional references & examples

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