Debugging

Express error handling in production: async errors, error middleware and what to log

How errors reach your error middleware in Express 4 and 5, how to map them to status codes, and what to log.

Express error handling in production: an Express error middleware with a res.headersSent check next to two JSON log lines, a 500 error with requestId and route GET /orders/:id and a 409 warning (illustrative)

This Express 4 route looks harmless:

js
app.get('/orders/:id', async (req, res) => {
  const order = await db.orders.findById(req.params.id); // rejects on a bad id
  res.json(order);
});

When findById rejects, Express 4 never hears about it. On Node 15 and later the default for an unhandled rejection is to raise it as an uncaught exception, so the process exits and takes every in-flight request with it. If someone added a process.on('unhandledRejection') handler that logs and carries on, the process survives, nothing ever answers that request, and the client waits until its own timeout. Neither outcome leaves a log line that names the route.

This post covers how errors reach Express 4 and 5, one error middleware that owns the response, a single error class for status codes, and what to log so on-call can find the request behind a 500.

How errors reach Express

A synchronous throw inside a handler is caught in both versions and passed to your error middleware. Promises are where the versions differ.

The Express error handling guide for version 5 says: “Route handlers and middleware that return a Promise call next(value) automatically when they reject or throw an error, and async functions always return a Promise, so their errors reach Express with no extra work.” On Express 5, the route above works as written.

Express 4 ignores the promise a handler returns. You can wrap each handler body in try...catch and call next(err) yourself, or write the wrapper once:

js
const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/orders/:id', asyncHandler(async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  if (!order) throw new HttpError(404, 'not_found', 'Order not found');
  res.json(order);
}));

Or upgrade. Async error forwarding is one of the changes in our Express 5 migration guide, along with the route syntax changes that take most of the migration time.

The gotcha Express 5 still has

Express 5 only sees promises the handler returns. Start one without returning or awaiting it, and its rejection happens outside Express:

js
app.get('/reports/:id', (req, res, next) => {
  loadReport(req.params.id).then((report) => res.json(report)); // no catch
});

The guide is direct about this case: “If the promise is not returned, Express does not know it exists,” and without a final catch “the rejection would be unhandled and crash the process” (working with promise chains). Return the promise, await it, or end the chain with .catch(next).

Work that runs after the response is a separate case. A welcome email sent after res.status(201).json(...) can’t change the response, so next won’t help the client. Catch it where you start it and log it:

js
sendWelcomeEmail(user).catch((err) => logger.error({ err }, 'welcome email failed'));

Callback APIs such as node:fs need the same care: the error arrives as the callback’s first argument, and you pass it to next(err) yourself.

One error middleware owns the response

Error middleware is any middleware with four arguments, (err, req, res, next), registered after every route and router (writing error handlers). Express skips it on normal requests and jumps to it when something calls next(err).

js
app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);

  const httpErr = toHttpError(err);
  const status = httpErr instanceof HttpError ? httpErr.status : 500;
  const expose = httpErr instanceof HttpError && httpErr.expose;

  logError(httpErr, req, res, status);

  res.status(status).json({
    error: {
      code: expose ? httpErr.code : 'internal_error',
      message: expose ? httpErr.message : 'Something went wrong',
      requestId: req.id,
    },
  });
});

The res.headersSent check is for responses that already started, such as a stream that fails halfway. You can’t send a JSON body at that point, so the docs say to hand the error to the default handler, which “closes the connection and fails the request” (the default error handler).

That default handler writes the stack trace to the client unless NODE_ENV is production. Set it in every deployed environment anyway, but let your own handler decide what the client sees.

req.id is the request ID set by your first middleware. If you don’t have one yet, AsyncLocalStorage request IDs walks through the setup. Putting it in the error body gives support a string a customer can paste into a ticket.

Map errors to status codes with one class

js
class HttpError extends Error {
  constructor(status, code, message, { expose = status < 500, cause } = {}) {
    super(message, { cause });
    this.name = 'HttpError';
    this.status = status;
    this.code = code;
    this.expose = expose;
  }
}

function toHttpError(err) {
  if (err instanceof HttpError) return err;
  if (err.name === 'ZodError') {
    return new HttpError(400, 'validation_failed', 'Invalid request body', { cause: err });
  }
  if (err.code === '23505') { // Postgres unique_violation
    return new HttpError(409, 'already_exists', 'That record already exists', { cause: err });
  }
  return err; // unknown: stays a 500
}

Throw HttpError where you know what went wrong (the 404 in the first handler), and translate library errors in toHttpError. Validation failures become 400, a missing record 404, and a unique-constraint violation 409 (Postgres reports it as SQLSTATE 23505 in its error codes appendix). Anything you didn’t map is a 500.

expose defaults to true below 500 and false at 500 and above. An unknown error’s message never goes to the client, because it can carry a SQL fragment or an internal hostname. The client gets internal_error and the request ID, and the details go to your logs.

What to log for every error

The log line is for whoever is on call with a request ID from a customer email. Give them the request ID, the method and route pattern (/orders/:id, so errors group by route instead of by every distinct URL), the status you sent, err.name and err.code, the err.cause chain, and how long the request ran.

js
import pino from 'pino';

const logger = pino({
  redact: {
    paths: ['req.headers.authorization', 'req.headers.cookie', 'req.body.password', 'req.body.token'],
    censor: '[Redacted]',
  },
});

// first middleware: start the clock
app.use((req, res, next) => {
  res.locals.startedAt = performance.now();
  next();
});

function causeChain(err) {
  const chain = [];
  for (let e = err; e && chain.length < 5; e = e.cause) {
    chain.push({ name: e.name, code: e.code, message: e.message });
  }
  return chain;
}

function logError(err, req, res, status) {
  logger[status >= 500 ? 'error' : 'warn']({
    requestId: req.id,
    method: req.method,
    route: req.route ? req.baseUrl + req.route.path : 'unmatched',
    status,
    errName: err.name,
    errCode: err.code,
    causes: causeChain(err),
    stack: status >= 500 ? err.stack : undefined,
    durationMs: Math.round(performance.now() - res.locals.startedAt),
  }, err.message);
}

logError never logs headers or bodies, which is the safest default. The redact paths cover the day someone adds req to a log call elsewhere. Keep authorization headers, passwords and full request bodies from auth routes (login, signup, password reset) out of logs entirely; redact sensitive data in logs has the longer list and a test that catches leaks.

4xx errors log at warn without a stack, since they are usually the client’s mistake. 5xx errors log at error with the stack.

Process-level handlers are the last line

Some errors will still get past Express: a timer callback, an event emitter with no error listener, a promise someone forgot. Catch them at the process level, log them, and exit:

js
process.on('unhandledRejection', (reason) => {
  logger.fatal({ err: reason }, 'unhandled rejection');
  process.exit(1);
});

process.on('uncaughtException', (err) => {
  logger.fatal({ err }, 'uncaught exception');
  process.exit(1);
});

Exiting is deliberate. The Node.js process docs say “unhandled exceptions inherently mean that an application is in an undefined state” and “it is not safe to resume normal operation after ‘uncaughtException’.” They recommend an external monitor in a separate process to restart the app, which is what systemd, Kubernetes or your platform’s restart policy already does.

An unhandledRejection handler replaces Node’s default of crashing. One that only logs is how the hanging request at the top of this post happens, so make sure yours exits.

Checklist for your PR template

  • [ ] Async handlers are covered: Express 5, or asyncHandler or try...catch on Express 4
  • [ ] Promises started in a handler are returned, awaited or end in .catch(next); work after the response catches and logs its own errors
  • [ ] One four-argument error middleware, registered after all routes, with a res.headersSent check
  • [ ] Errors the client should see are HttpError with expose; unknown errors return a generic body with the request ID
  • [ ] Error logs carry request ID, route pattern, status, err.name, err.code, cause chain and duration, and never auth headers, passwords or auth-route bodies
  • [ ] unhandledRejection and uncaughtException log and exit, and NODE_ENV=production is set in every deployed environment

ApiTraffic’s Errors view lists every request your API answered with a status code of 400 or higher, so you can find the request behind a 500 by its status and time. See what’s hitting your API: apitraffic.io

Keep reading