Error handling in Express

Topic 4 of 4 in Express6 min readIntermediateFree course

Overview

Errors are certain: users send bad data, records don’t exist, databases time out, and you will write bugs. A good API handles all of them consistently — every error response has the same shape, the right status code, and a helpful message, while technical details stay in your logs and out of attackers’ hands.

Express makes this possible with one special kind of middleware: the error handler.

The error handler

An error-handling middleware is any middleware with four parameters:

JavaScript
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: { message: 'Something went wrong' } });
});

Express knows it’s an error handler purely because it takes four arguments — so keep all four, even if you don’t use next. Register it after all your routes.

How errors get there

A request passes through json(), auth and getCourse. getCourse throws or its promise rejects, so Express skips the remaining notFound middleware and jumps straight to the four-parameter error handler, which sends a 4xx or 500 JSON response. Express 5 catches errors thrown in async handlers; the error handler is registered last and decides what the client may see.

Any of these sends control straight to the error handler, skipping all normal middleware and routes in between:

JavaScript
app.get('/a', (req, res) => {
  throw new Error('sync throw');            // caught by Express
});

app.get('/b', async (req, res) => {
  await db.query('…');                       // a rejection is caught too (Express 5)
});

app.get('/c', (req, res, next) => {
  fs.readFile('x', (err, data) => {
    if (err) return next(err);               // callbacks must call next(err) themselves
    res.send(data);
  });
});

The one case Express can’t catch on its own is an error inside a callback that runs later — pass it to next(err) yourself (or use promise APIs, which avoid the problem).

Custom error classes

Throwing a plain Error loses an important piece of information: which status code the client should get. Create an error class that carries it:

JavaScript
// src/errors.js
export class HttpError extends Error {
  constructor(status, message, details) {
    super(message);
    this.name = 'HttpError';
    this.status = status;
    this.details = details;
  }
}

export const notFoundError = (what) => new HttpError(404, `${what} not found`);
export const badRequest = (message, details) => new HttpError(400, message, details);

Handlers then just throw — no response-building code scattered everywhere:

JavaScript
app.get('/courses/:id', async (req, res) => {
  const course = await coursesRepo.findById(req.params.id);
  if (!course) throw notFoundError('Course');
  res.json(course);
});

The 404 handler

When no route matches, Express’s default is an HTML “Cannot GET /x” page — not ideal for an API. Add a catch-all after your routes and before the error handler:

JavaScript
app.use((req, res, next) => {
  next(new HttpError(404, `No route for ${req.method} ${req.originalUrl}`));
});

A production-ready error handler

JavaScript
// src/middleware/error-handler.js
import { HttpError } from '../errors.js';

export function errorHandler(err, req, res, next) {
  // If streaming a response already started, let Express close the connection
  if (res.headersSent) return next(err);

  // Body parser errors (malformed JSON, body too large) carry a status already
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: { message: 'Request body is not valid JSON' } });
  }
  if (err.type === 'entity.too.large') {
    return res.status(413).json({ error: { message: 'Request body is too large' } });
  }

  // Errors we created on purpose: safe to show the message
  if (err instanceof HttpError) {
    return res.status(err.status).json({
      error: { message: err.message, details: err.details },
    });
  }

  // Anything else is a bug or an outage: log everything, reveal nothing
  req.log?.error({ err }, 'Unhandled error') ?? console.error(err);
  res.status(500).json({ error: { message: 'Something went wrong. Please try again.' } });
}
JavaScript
// src/app.js — the order matters
app.use('/api/v1', apiRouter);
app.use(notFound);
app.use(errorHandler);

Never leak internals

A raw error message can reveal SQL, file paths, library versions or other details that help attackers. Only intentional errors (HttpError) have their messages shown. Everything else becomes a generic 500, with the full error in your logs.

In development it can be handy to include the stack trace — but guard it carefully:

JavaScript
const body = { error: { message: 'Something went wrong' } };
if (process.env.NODE_ENV === 'development') body.error.stack = err.stack;

A consistent error format

Pick one error shape and use it everywhere. Clients can then handle errors with one piece of code:

JSON
{
  "error": {
    "message": "Validation failed",
    "details": [
      { "path": "email", "message": "Invalid email address" },
      { "path": "password", "message": "Must be at least 12 characters" }
    ]
  }
}

Some teams adopt the Problem Details standard (RFC 9457), with fields such as type, title, status and detail and the application/problem+json content type. Either is fine — consistency is what matters.

Errors outside requests

The error handler only covers errors during a request. Errors in background tasks, timers, or start-up code still need handling — and truly unexpected errors should be logged and the process restarted, as covered in Error handling in Node.

One place for error formatting means one place to add logging, error-tracking (such as Sentry) or translations later. Throw anywhere; respond in one place.

Exercise

A complete error setup

Create an HttpError class with a status, a notFound handler for unknown routes, and an errorHandler that: returns { error: { message } } with the right status for HttpErrors, returns 400 for malformed JSON bodies, and returns a generic 500 (logging the details) for anything else.

JavaScript
export class HttpError extends Error {}

export function notFound(req, res, next) {}

export function errorHandler(err, req, res, next) {}

Summary

  • An error-handling middleware has four parameters: (err, req, res, next), and is registered last.
  • Express 5 sends thrown errors and rejected promises from handlers to it automatically.
  • Throw custom errors with a status (e.g. HttpError(404, …)) and let one handler format every response.
  • Add a catch-all 404 handler after your routes.
  • Never send stack traces or internal messages to clients in production — log them instead.