EthicsComputerCourses
Join training +91 90532 10052

Error Handling & Middleware

MERN Stack · Lesson 7 of 20 Intermediate 11 min read Updated

By the end of this lesson every error in the TaskBoard API, expected or not, will flow to one place and leave as the same JSON shape. You will create an HttpError class, turn Mongoose, MongoDB and body-parser errors into the right status codes, answer a duplicate email with 409 Conflict, and give every request an id that links what the user saw to the line in your server log.

What you should know first: CRUD Endpoints & Validation, whose files this lesson tidies up. General Express error handling is covered in Error Handling and Middleware in the Node.js course. Versions checked: Express 5.3.0, Mongoose 9.12.1, Zod 4.6.7, with every output below taken from a real run.

Two kinds of errors

Picture a bank counter in Jaipur. If your balance is too low, the cashier tells you exactly that, because it is your problem and you can fix it. If the cash machine behind the counter jams, the cashier does not explain the machine's wiring; they say "please wait, we are sorting it out" and call the engineer.

APIs meet the same two kinds of errors:

KindExamples in TaskBoardStatusWhat the client sees
Expected (the client can fix it)missing title, unknown task, email already used400, 404, 409A clear message, and details per field
Unexpected (a bug or an outage)a typo in code, database down500Only "Something went wrong"

Expected errors are part of the API contract, so their messages are written for users. Unexpected errors are written for developers, so their details go to the server log and nowhere else.

Right now TaskBoard handles expected errors in many places with return res.status(...).json({ error: ... }). Each copy is a chance to get the shape wrong. Express 5 offers a cleaner way: throw the error, and let one error-handling middleware write every reply. Express 5 catches errors thrown in normal handlers and rejected promises from async handlers and passes them to the error handler.

Step 1: An error that knows its status

Create server/src/utils/httpError.js:

JavaScript
// An error that already knows its HTTP status. Its message is safe to show the client.
export class HttpError extends Error {
  constructor(status, message, details) {
    super(message);
    this.name = "HttpError";
    this.status = status;
    this.details = details;
  }
}

Now code anywhere can say throw new HttpError(404, "Task not found") and stop. Rewrite server/src/middleware/validate.js to throw instead of replying:

JavaScript
// Checks req.body or req.query against a Zod schema; a failure becomes a 400 HttpError.
import { HttpError } from "../utils/httpError.js";

function check(schema, value) {
  const result = schema.safeParse(value);
  if (!result.success) {
    const details = result.error.issues.map((issue) => ({
      field: issue.path.join(".") || "body",
      message: issue.message,
    }));
    throw new HttpError(400, "Validation failed", details);
  }
  return result.data;
}

export const validateBody = (schema) => (req, res, next) => {
  req.body = check(schema, req.body ?? {});
  next();
};

export const validateQuery = (schema) => (req, res, next) => {
  res.locals.query = check(schema, req.query);
  next();
};

The id check from the tasks router becomes a reusable middleware, server/src/middleware/objectIdParam.js, so the users router can share it:

JavaScript
import mongoose from "mongoose";
import { HttpError } from "../utils/httpError.js";

// For router.param("id", ...): a malformed id can never match a document, so answer 404 at once.
export function objectIdParam(label) {
  return (req, res, next, id) => {
    if (!mongoose.isObjectIdOrHexString(id)) throw new HttpError(404, `${label} not found`);
    next();
  };
}

In tasks.routes.js, delete the inline param function and the mongoose import, and write tasksRouter.param("id", objectIdParam("Task")); instead. The controller shrinks too:

JavaScript
import { Task, User } from "../models/index.js";
import { HttpError } from "../utils/httpError.js";

async function assertAssigneeExists(assignee) {
  if (assignee && !(await User.exists({ _id: assignee }))) {
    throw new HttpError(400, "Validation failed", [{ field: "assignee", message: "No user with this id" }]);
  }
}

async function findTaskOr404(id) {
  const task = await Task.findById(id);
  if (!task) throw new HttpError(404, "Task not found");
  return task;
}

export async function listTasks(req, res) {
  const { status, assignee, limit } = res.locals.query;
  const filter = {};
  if (status) filter.status = status;
  if (assignee) filter.assignee = assignee;
  const tasks = await Task.find(filter).sort({ dueDate: 1 }).limit(limit).populate("assignee", "name");
  res.json(tasks);
}

export async function getTask(req, res) {
  const task = await findTaskOr404(req.params.id);
  res.json(await task.populate("assignee", "name"));
}

export async function createTask(req, res) {
  await assertAssigneeExists(req.body.assignee);
  const task = await Task.create(req.body);
  await task.populate("assignee", "name");
  res.status(201).location(`/api/tasks/${task.id}`).json(task);
}

export async function updateTask(req, res) {
  await assertAssigneeExists(req.body.assignee);
  const task = await findTaskOr404(req.params.id);
  task.set(req.body);
  await task.save();
  res.json(await task.populate("assignee", "name"));
}

export async function deleteTask(req, res) {
  const task = await Task.findByIdAndDelete(req.params.id);
  if (!task) throw new HttpError(404, "Task not found");
  res.status(204).end();
}

Every handler now reads as the happy path: the normal flow when nothing goes wrong. Each throw leaves the function at once, so there are no if (problem) return lines to forget. Finally notFound.js throws too:

JavaScript
import { HttpError } from "../utils/httpError.js";

export function notFound(req, res) {
  throw new HttpError(404, `No route for ${req.method} ${req.originalUrl}`);
}

Step 2: Translate errors in one place

Replace server/src/middleware/errorHandler.js. It works like a translator at a government office: whatever language an error arrives in, it leaves in the API's language.

JavaScript
// The last middleware: turns any error into the API's JSON error shape.
import { HttpError } from "../utils/httpError.js";

// Known error types become an HttpError. Anything else returns null: it is a bug.
function translate(err) {
  if (err instanceof HttpError) return err;
  if (err.name === "ValidationError") {
    const details = Object.values(err.errors).map((e) => ({ field: e.path, message: e.message }));
    return new HttpError(400, "Validation failed", details);
  }
  if (err.name === "CastError") {
    return new HttpError(400, "Validation failed", [{ field: err.path, message: `Invalid value for ${err.path}` }]);
  }
  if (err.code === 11000) {
    const field = Object.keys(err.keyValue ?? {})[0] ?? "value";
    return new HttpError(409, `That ${field} is already in use`, [{ field, message: "Already in use" }]);
  }
  if (err.expose && err.status < 500) {
    return new HttpError(err.status, err.message); // for example broken JSON from express.json()
  }
  return null;
}

export function errorHandler(err, req, res, next) {
  if (res.headersSent) return next(err);
  const known = translate(err);
  if (!known) {
    console.error(`[${req.id}] ${req.method} ${req.originalUrl}`, err);
    return res.status(500).json({ error: { message: "Something went wrong" } });
  }
  const error = { message: known.message };
  if (known.details) error.details = known.details;
  res.status(known.status).json({ error });
}
Error arrivingWhere it comes fromReply
HttpErrorour own codeits status, message and details
ValidationErrora Mongoose validator on save400 with one detail per field
CastErrora value Mongoose cannot convert, such as text for a date400
code 11000MongoDB unique index, such as a second user with the same email409 Conflict
expose: true, status below 500express.json(): broken JSON (400), body over 10 KB (413)its own status and message
anything elsea bug or an outage500, details only in the log

res.headersSent is true if a reply has already started, for example halfway through a large download. You cannot change the status code then, so the handler passes the error to Express's built-in handler, which closes the connection.

Step 3: A route that can conflict

Admins will need to add staff, so add POST /api/users, plus GET /api/users/:id so that the Location header points somewhere real. Create server/src/validation/users.validation.js:

JavaScript
import { z } from "zod";

export const createUserSchema = z.object({
  name: z.string("Name is required").trim().min(1, "Name is required").max(80, "Name must be 80 characters or fewer"),
  email: z.email("Enter a valid email address"),
  role: z.enum(["admin", "teacher"], "role must be admin or teacher").optional(),
});

Add two functions to users.controller.js (import HttpError at the top) and wire them in users.routes.js:

JavaScript
// users.controller.js
export async function getUser(req, res) {
  const user = await User.findById(req.params.id).select("name role");
  if (!user) throw new HttpError(404, "User not found");
  res.json(user);
}

export async function createUser(req, res) {
  const user = await User.create(req.body);
  res.status(201).location(`/api/users/${user.id}`).json(user);
}

// users.routes.js
import { listUsers, getUser, createUser } from "../controllers/users.controller.js";
import { objectIdParam } from "../middleware/objectIdParam.js";
import { validateBody } from "../middleware/validate.js";
import { createUserSchema } from "../validation/users.validation.js";
// ...
usersRouter.param("id", objectIdParam("User"));
usersRouter.get("/", listUsers);
usersRouter.get("/:id", getUser);
usersRouter.post("/", validateBody(createUserSchema), createUser);

createUser has no duplicate check of its own. Checking "does this email exist?" before saving has a gap: two requests at the same moment can both pass the check. The unique index in MongoDB is the only reliable guard, so we let it fail and translate the error. Posting Priya's email in different capitals:

Output
POST /api/users {"name":"Priya S","email":"Priya@Example.com"}
  409 {"error":{"message":"That email is already in use","details":[{"field":"email","message":"Already in use"}]}}
POST /api/users {"name":"Meera Iyer","email":"meera@example.com"}
  201 Location: /api/users/6afa9a2d9f1579c5af6a7110
POST /api/users {"name":"","email":"meera-at-example","role":"principal"}
  400 {"error":{"message":"Validation failed","details":[{"field":"name","message":"Name is required"},{"field":"email","message":"Enter a valid email address"},{"field":"role","message":"role must be admin or teacher"}]}}

The first request clashed even with different capitals, because the User schema has lowercase: true, so the email was stored as priya@example.com.

Step 4: Request ids and a request log

When a teacher says "it showed an error at 4 pm", you need to find that request among thousands. Give every request an id. Create server/src/middleware/requestLogger.js:

JavaScript
import { randomUUID } from "node:crypto";

// Gives every request an id (sent back as X-Request-Id) and logs one line when it finishes.
export function requestLogger(req, res, next) {
  req.id = randomUUID();
  res.set("X-Request-Id", req.id);
  const start = performance.now();
  res.on("finish", () => {
    const ms = (performance.now() - start).toFixed(1);
    console.log(`${req.id.slice(0, 8)} ${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
  });
  next();
}

randomUUID() makes a random UUID, a 36-character id that is practically never repeated. The finish event fires after the reply is sent, so the log line knows the final status. In app.js, import it and add app.use(requestLogger); straight after helmet(), so even CORS and JSON errors are logged. The server log for the requests in this lesson looks like this:

Output
3b2caba6 POST /api/users 409 540.2ms
64793229 POST /api/users 201 225.4ms
b2681508 POST /api/users 400 65.7ms
3e4f6d97 GET /api/tasks/abc 404 11.3ms
f4596fab GET /api/students 404 2.5ms
2096f3c8 POST /api/tasks 400 12.5ms
c3861c82 POST /api/tasks 413 56.4ms

For production, a structured logger such as pino writes the same facts as JSON lines that log tools can search; see Logging.

Step 5: When something really breaks

To see the unexpected path, we put a typo in listTasks on purpose, writing Task.fnd(filter). The client got this:

Output
HTTP/1.1 500 Internal Server Error
X-Request-Id: 7f49fa77-4aec-416d-b2dc-4b194bd3d371
{"error":{"message":"Something went wrong"}}

And the server log said (stack trace shortened to its first two lines):

Output
[7f49fa77-4aec-416d-b2dc-4b194bd3d371] GET /api/tasks?status=todo TypeError: Task.fnd is not a function
    at listTasks (file:///C:/Users/meera/code/taskboard/server/src/controllers/tasks.controller.js:21:28)
    at Layer.handleRequest (C:\Users\meera\code\taskboard\node_modules\router\lib\layer.js:152:17)
7f49fa77 GET /api/tasks?status=todo 500 86.4ms

The user learns nothing about your code, but anyone holding the X-Request-Id can find the exact stack trace. Fix the typo before moving on.

Errors outside a request are different. A rejected promise that nobody awaits, or an error thrown inside a setTimeout, never reaches Express. Since Node.js 15, an unhandled promise rejection crashes the process by default. That sounds harsh, but it is the safe choice: after an unknown failure, the program's state cannot be trusted. Let it stop, log the reason, and let a process manager or your host restart it, as covered in Deploying a MERN App.

How the client uses these errors

Because every error has one shape, the React side needs one small piece of logic. The example below uses real replies from this lesson. It shows field messages under the matching inputs, the conflict message under the email field, and the request id for a 500.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const replies = {
  "Bad task": { status: 400, body: { error: { message: "Validation failed", details: [
    { field: "title", message: "Title is required" },
    { field: "status", message: "status must be one of: todo, doing, done" },
    { field: "dueDate", message: "dueDate must be a date like 2026-11-25" }] } } },
  "Duplicate email": { status: 409, body: { error: { message: "That email is already in use",
    details: [{ field: "email", message: "Already in use" }] } } },
  "Server bug": { status: 500, body: { error: { message: "Something went wrong" } },
    requestId: "7f49fa77-4aec-416d-b2dc-4b194bd3d371" },
};

// One function turns any error reply into what the screen needs.
function readError(reply) {
  const fields = Object.fromEntries((reply.body.error.details ?? []).map((d) => [d.field, d.message]));
  let banner = reply.body.error.message;
  if (reply.status >= 500) banner += `. If it keeps happening, quote this id: ${reply.requestId.slice(0, 8)}`;
  return { banner, fields };
}

function Field({ name, problems }) {
  return (
    <p>
      <label>{name} <input /></label>
      {problems[name] && <span style={{ color: "crimson" }}> {problems[name]}</span>}
    </p>
  );
}

function ErrorDemo() {
  const [shown, setShown] = useState({ banner: "", fields: {} });
  return (
    <div>
      {Object.keys(replies).map((label) => (
        <button key={label} onClick={() => setShown(readError(replies[label]))}>{label}</button>
      ))}
      {shown.banner && <p role="alert"><strong>{shown.banner}</strong></p>}
      {["title", "status", "dueDate", "email"].map((name) => <Field key={name} name={name} problems={shown.fields} />)}
    </div>
  );
}

createRoot(document.getElementById("root")).render(<ErrorDemo />);

"Bad task" puts three messages next to title, status and dueDate. "Duplicate email" marks only the email field. "Server bug" shows no field messages, just "Something went wrong. If it keeps happening, quote this id: 7f49fa77". You will build the real forms in Forms, Validation & Errors.

Common mistakes

  • An error handler with three parameters. Express recognises error middleware only by its four parameters (err, req, res, next). Keep next even if you do not use it.
  • Sending err.message for every error. A database error message can reveal collection names and internal values. Only HttpError and expose errors are safe to show.
  • Checking for duplicates with findOne before saving. Two requests can pass at the same moment. Rely on the unique index and translate code 11000.
  • Swallowing errors with an empty catch {}. The bug disappears from the log but not from the app. Let errors reach the handler.
  • Using process.on("uncaughtException") to keep the server running. Log the error and exit; restart cleanly.

Interview questions

1. How does Express 5 handle an error thrown inside an async route handler?

If the handler throws or its promise rejects, Express 5 passes the error to the next error-handling middleware, just like calling next(err). Express 4 did not catch rejected promises, so code needed try/catch or a wrapper such as express-async-handler.

2. Why return 409 Conflict for a duplicate email instead of 400?

The request is well formed and valid on its own; it conflicts with the current state of the server, where that email already exists. 409 tells the client exactly that, so the screen can say "this email is already registered" rather than "invalid input".

3. Why should 500 replies hide error details?

Stack traces and database messages reveal file paths, library versions and data names, which help attackers plan. They also mean nothing to users. Log the details with a request id on the server and send a generic message.

4. What is a request id used for?

It ties one request to every log line it produced, across middleware and services. Sending it back in a header such as X-Request-Id lets support staff ask the user for it and find the exact error in the logs.

Key points

  • Throw new HttpError(status, message, details) for expected errors; Express 5 delivers it to the error handler.
  • One errorHandler translates ValidationError and CastError to 400, duplicate key 11000 to 409, and express.json() errors to their own status.
  • Anything not recognised is a bug: log it with the request id, reply 500 "Something went wrong".
  • Let the unique index catch duplicates; a check-then-insert can race.
  • requestLogger gives each request an X-Request-Id and logs method, URL, status and time.
  • Errors outside requests crash the process; restart it cleanly instead of ignoring them.

Exercise

A client that sends a body over 10 KB now gets 413 with the message "request entity too large". Make the reply friendlier: "Request body is too large (limit 10 KB)". The error object from express.json() has a type property; find out its value for this case and add a branch to translate. Test with a JSON body that has a 20,000-character title.

Show solution
JavaScript
// errorHandler.js, inside translate(), before the "expose" branch
if (err.type === "entity.too.large") {
  return new HttpError(413, "Request body is too large (limit 10 KB)");
}
Output
HTTP/1.1 413 Payload Too Large
{"error":{"message":"Request body is too large (limit 10 KB)"}}

The branch must come before the general expose branch, because translate returns the first match. Checking err.type is safer than matching the message text, which a library update could change.

Quick Quiz

1. What must an Express error-handling middleware look like?

2. A second user is saved with an existing email. Which reply does TaskBoard send?

3. What does the client see when a controller has a typo such as Task.fnd?

4. Why is checking User.findOne({ email }) before User.create() not enough to stop duplicates?

Learn MERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call