Lesson 5 of 8 · 13 min · Building APIs with Express
Express error handling and request validation
What you will learn
- Write error-handling middleware and the 404 handler
- Create custom error classes that carry an HTTP status
- Understand how async errors flow in Express 5
- Validate request bodies, params and queries with Zod
- Return consistent, safe error responses and log them once
In simple words
Things go wrong in every API: someone sends a broken request, a database is down, a bug throws. Without a plan, the server leaks stack traces or crashes. A central error handler is the complaints desk: any error from any route ends up there, and it replies with the right status code and a tidy message. Validation is the bouncer at the door that rejects bad input before it reaches your logic.
Words to know
- Error-handling middleware: middleware with four arguments
(err, req, res, next)that handles errors. - Operational error: an expected failure, such as invalid input or "not found".
- Programmer error: a bug, such as reading a property of
undefined. - Schema: a description of the shape and rules of valid data.
Error-handling middleware
Express recognises an error handler by its four parameters. It goes after all routes and other middleware:
// src/middleware/errors.js
export function notFound(req, res) {
res.status(404).json({ type: "about:blank", title: "Not Found", status: 404, detail: `No route for ${req.method} ${req.path}` });
}
export function errorHandler(err, req, res, next) {
if (res.headersSent) return next(err); // too late to change the response: delegate to Express
const status = err.status ?? err.statusCode ?? 500;
const expected = status < 500;
if (!expected) console.error({ err, requestId: req.id }, "Unhandled error"); // log the stack for server errors
res.status(status).json({
type: "about:blank",
title: expected ? err.title ?? "Request failed" : "Internal Server Error",
status,
detail: expected ? err.message : "Something went wrong.", // never leak internals for 5xx
...(err.errors && { errors: err.errors }),
});
}
// server.js
app.use("/api", routes);
app.use(notFound);
app.use(errorHandler);
The response format above follows RFC 9457 problem details (the same standard used in the Spring Boot course). Rules:
- A 5xx must not reveal messages, SQL, file paths or stack traces to clients; log them on the server.
- Check
res.headersSentbefore writing. - The error handler is the one place that turns errors into HTTP responses, and the best place to log (once).
Custom error classes
export class HttpError extends Error {
constructor(status, message, options = {}) {
super(message, { cause: options.cause });
this.name = this.constructor.name;
this.status = status;
this.title = options.title;
this.errors = options.errors;
}
}
export class NotFoundError extends HttpError {
constructor(what, id) { super(404, `${what} ${id} was not found`, { title: "Not Found" }); }
}
export class ConflictError extends HttpError {
constructor(message) { super(409, message, { title: "Conflict" }); }
}
export class UnauthorizedError extends HttpError {
constructor(message = "Sign in required") { super(401, message, { title: "Unauthorized" }); }
}
export class ForbiddenError extends HttpError {
constructor(message = "You are not allowed to do this") { super(403, message, { title: "Forbidden" }); }
}
Services throw domain errors; the handler maps them:
// services/orders.js
export async function getOrder(id) {
const order = await db.orders.findById(id);
if (!order) throw new NotFoundError("Order", id);
return order;
}
Match status codes to meaning: 400 invalid input, 401 not authenticated, 403 not allowed, 404 missing, 409 conflict (duplicate, version mismatch), 422 semantic validation (some teams), 429 too many requests, 500 bug, 502/503/504 dependency problems. Translate low-level errors (a database unique-constraint violation, error code 23505 in PostgreSQL) into a ConflictError at the data layer, keeping the cause.
Async errors in Express 5
In Express 5, if a route handler or middleware returns a rejected promise (or an async function throws), Express calls the error handler for you. No wrapper is needed:
app.get("/orders/:id", async (req, res) => {
const order = await getOrder(Number(req.params.id)); // throws NotFoundError -> errorHandler
res.json(order);
});
In Express 4 an async error was lost (the request hung) unless you wrote try/catch with next(err) or used express-async-errors. Synchronous throw in a handler also reaches the error handler. Errors thrown in callbacks of old-style APIs (setTimeout, event emitters) are not caught by Express: wrap them in promises, or call next(err) yourself. Errors in a stream must be handled with pipeline.
Safety nets
process.on("unhandledRejection", (reason) => { console.error({ reason }, "unhandled rejection"); process.exit(1); });
process.on("uncaughtException", (error) => { console.error({ error }, "uncaught exception"); process.exit(1); });
These catch programmer errors that escaped everything. After them the process state is unreliable, so log and exit, and let a supervisor restart it (the runtime lesson). Distinguish operational errors (handled by returning a response) from programmer errors (fix the bug).
Validation: never trust input
Everything in req.body, req.query, req.params and headers comes from the outside and may be missing, the wrong type, too large or malicious. Validate at the edge, before the data reaches business logic or the database, and validate again where it matters (the database has constraints too).
Zod defines a schema, validates data and infers a TypeScript type:
npm install zod
import { z } from "zod";
export const createOrderSchema = z.object({
customerId: z.number().int().positive(),
productIds: z.array(z.number().int().positive()).min(1).max(50),
note: z.string().trim().max(200).optional(),
coupon: z.string().regex(/^[A-Z0-9]{4,12}$/).optional(),
});
export const listOrdersQuery = z.object({
status: z.enum(["paid", "pending", "refunded"]).optional(),
page: z.coerce.number().int().min(1).default(1), // query values are strings: coerce
size: z.coerce.number().int().min(1).max(100).default(20),
});
export const idParam = z.object({ id: z.coerce.number().int().positive() });
A reusable validation middleware:
import { HttpError } from "./errors.js";
export const validate = (schema, source = "body") => (req, res, next) => {
const result = schema.safeParse(req[source]);
if (!result.success) {
const errors = result.error.issues.map((i) => ({ field: i.path.join("."), message: i.message }));
return next(new HttpError(400, "Validation failed", { title: "Invalid request", errors }));
}
Object.defineProperty(req, `valid${source[0].toUpperCase()}${source.slice(1)}`, { value: result.data }); // req.validBody
next();
};
// usage
router.get("/", validate(listOrdersQuery, "query"), async (req, res) => {
const { status, page, size } = req.validQuery; // typed, defaulted, coerced
res.json(await orders.list({ status, page, size }));
});
router.post("/", validate(createOrderSchema), async (req, res) => {
const created = await orders.create(req.validBody);
res.status(201).location(`/api/orders/${created.id}`).json(created);
});
(In Express 5 req.query is read-only, so store parsed values in a new property such as req.validQuery, as above.) A failed request returns:
{
"title": "Invalid request",
"status": 400,
"detail": "Validation failed",
"errors": [
{ "field": "productIds", "message": "Array must contain at least 1 element(s)" },
{ "field": "customerId", "message": "Expected number, received string" }
]
}
Alternatives: express-validator (chains of rules per field), Joi, Ajv with JSON Schema (fast, shareable with OpenAPI), Valibot. The best arrangement shares one schema between client and server (a package or a monorepo).
Validation rules worth having
- Types and presence: required versus optional,
nullhandling. - Ranges and lengths:
min,max, array sizes; limit body size (express.json({ limit })), upload size, and the number of items in lists. - Formats: email, URL, UUID, ISO dates, phone patterns, enums for fixed sets.
- Allow-lists, not block-lists: accept known fields only; strip unknown fields (
z.object(...).strict()rejects them, default.strip()removes them), which prevents mass assignment (a client settingrole: "admin"orprice). - Business rules (stock available, coupon valid) belong in the service layer, as they need data.
- Sanitisation vs validation: validate first; normalise (
trim, lower-case emails) where appropriate; encode output for its context (HTML, SQL via parameters), not by stripping characters at input. - Never build SQL from input: use parameterised queries or an ORM (the SQL course).
- Prevent prototype pollution and NoSQL injection: reject keys such as
__proto__, and validate that values are primitives, not objects with operators ({ "$gt": "" }in MongoDB filters). - Path traversal: never join user input to a file path without resolving and checking it against a base directory.
Testing error paths
With the built-in test runner and supertest:
import test from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { app } from "../src/app.js";
test("rejects an order without products", async () => {
const res = await request(app).post("/api/orders").send({ customerId: 1, productIds: [] });
assert.equal(res.status, 400);
assert.equal(res.body.errors[0].field, "productIds");
});
test("unknown order returns 404 problem", async () => {
const res = await request(app).get("/api/orders/999999");
assert.equal(res.status, 404);
});
test("unexpected errors do not leak details", async () => {
const res = await request(app).get("/api/boom"); // a route that throws
assert.equal(res.status, 500);
assert.equal(res.body.detail, "Something went wrong.");
});
Test failures as seriously as successes: invalid JSON (express.json() itself throws a 400 SyntaxError for malformed bodies, which your handler should map), oversized bodies (413), wrong content type, missing auth, and database failures.
Common mistakes
- Putting the error handler before the routes or giving it three arguments.
- Sending stack traces or raw error messages to clients.
- Swallowing errors in
catchblocks without logging or rethrowing. - Validating only in the front end.
- Forgetting that query and path values are strings (
"5", not5). - Trusting
req.bodyfields and passing the whole body to the database (mass assignment). - Logging the same error at several layers.
- No limit on body size or array length.
Try it yourself
- Add the
notFoundanderrorHandlermiddleware and make a route throw each ofNotFoundError,ConflictErrorand a plainError; compare responses. - Write a Zod schema for creating an order, plus the
validatemiddleware, and send good and bad requests withcurl. - Add query validation with coercion and defaults for pagination.
- Send
{"customerId":1,"productIds":[1],"role":"admin"}and show that unknown fields are rejected or stripped. - Write tests for 400, 404 and 500 responses with supertest.
Check yourself
How does Express recognise an error-handling middleware?
By its four parameters (err, req, res, next); it must be registered after the routes and other middleware.
How are errors in async handlers handled in Express 5?
A rejected promise or thrown error in an async handler is passed to the error handler automatically, without wrappers.
Why must input be validated on the server?
Clients can be bypassed with any HTTP tool, so only server-side validation protects the application from malformed or malicious data.
What is mass assignment and how do you prevent it?
A client sets fields it should not (such as role or price) because the server copies the whole body; prevent it by validating against a schema that allows only known fields.
Interview questions
How do you handle errors centrally in an Express API?
Services throw domain error classes with a status, async handlers rely on Express 5's forwarding of rejections, and one error middleware after all routes maps errors to a consistent problem-details JSON, hides internals for 5xx and logs once; a 404 handler catches unknown routes.
What is the difference between operational and programmer errors?
Operational errors are expected runtime problems (bad input, not found, timeouts) that you handle by responding; programmer errors are bugs (null access, wrong types) that should be fixed, and after an uncaught one the process should log and restart.
How would you validate requests?
Define schemas (Zod, Joi, Ajv) for body, query and params, run them in middleware before the controller, coerce string inputs, reject or strip unknown fields, return 400 with field-level messages and enforce limits on sizes.
Summary
- One four-argument error middleware after all routes turns errors into safe, consistent responses; a 404 handler precedes it.
- Custom error classes carry status codes; Express 5 forwards async errors; process-level handlers log and exit on bugs.
- Validate body, query and params with schemas (Zod) at the edge, coerce strings, strip unknown fields and set size limits.
- Test error paths, never leak internals, and log each error once.
Going deeper
- Express: Error handling: default handler, custom handlers and async errors.
- Zod documentation: schemas, parsing and inference.
- OWASP: Input Validation Cheat Sheet: what and how to validate.
- Node.js: Error handling: error classes,
causeand codes.
See how much of this you can explain
A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.