// ERROR HANDLING FOR FUN & PROFIT IN EXPRESS

Error Handling For Fun & Profit in Express

Jul 11, 2023 · Phil Borel · 6 min read

Note: this is an old post, ported from my old blog. Most of it dates from mid-2023, when we were cleaning up error handling in RIVET's Express API. The section on logging was added in 2025. The code samples are simplified sketches of the pattern, not RIVET's actual source.


Goal

Standardize error handling throughout server code to decrease bugs & reduce the complexity of writing new code & modifying existing code. Consolidate router-level error handling into one place using purpose-specific middleware.

Why doesn't node/express already do this for me?

(Update from the future: Express 5 has since shipped. It forwards rejected promises from async handlers to your error middleware, which removes one of the reasons for try/catch listed below. Everything else here still applies.)

Benefits

Less code

Less code has many sub-benefits:

  • decreased complexity
  • improved readability
  • simpler discovery
  • less time to release new features because a standard part of the work is handled in a standardized way
  • lower chance for bugs to occur because there are no divergent implementations of the same error-handling logic throughout the codebase
  • faster build time

Standardized error handling process

Increase error occurrence visibility by avoiding issues where one controller logs errors to Datadog & Sentry and another logs errors to the server's console & saves them to an error.log file. This allows you to debug issues more quickly, saving you valuable time to do more important things like not staying up all night to fix production outages.


Steps

  1. Create standardized error definitions
  2. Create purpose-built error-handling middleware: custom errors, invalid routes & unhandled errors
  3. Replace returning 500s with throwing errors, & console.error with your logger
  4. Bonus: know when you should still use try/catch
  5. Bonus: decide what actually deserves to be logged as an error

Throwing Errors

Standardized error definitions

Give the codebase one vocabulary for errors. We wrapped http-errors in a small helper so nobody has to remember status codes or invent message formats:

// helpers/errors.ts
import createError from 'http-errors';

export const AppErrors = {
  badRequest: (message = 'Bad Request') => createError(400, message),
  unauthorized: (message = 'Unauthorized') => createError(401, message),
  forbidden: (message = 'Access Denied') => createError(403, message),
  notFound: (message = 'Not Found') => createError(404, message),
  internalServerError: (cause?: unknown) => createError(500, 'Internal Server Error', { cause }),
};

Instances of throwing errors

Anywhere in the request lifecycle (controllers, actions, services), throw one of these instead of building a response by hand:

// before
throw createError(403, 'Access Denied for that role');

// after
throw AppErrors.forbidden('Access Denied for that role');

Catching Errors

LET 500s PASS THROUGH.

If something unexpected blows up, you don't need to catch it where it happened. Let it travel up to a single fallback handler that logs it & responds with a 500.

Once that fallback exists, you can remove all of these from your request lifecycle (middlewares & controllers):

export const readProfile = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const view = await profileView(req.user, id);
    if (view) {
      return res.json(view);
    } else {
      return res.status(404).json({ message: '404: Worker not found' });
    }
  } catch (error) {
    console.error(error);
    return res.status(error.status || 500).json({ message: error.message || 'internal server error' });
  }
};

The catch block there is doing three jobs (logging, picking a status code, shaping the response body) & every controller does those jobs slightly differently. With the middleware below in place, the controller shrinks to the part that's actually about profiles:

export const readProfile = async (req: Request, res: Response) => {
  const id = Number(req.params.id);
  const view = await profileView(req.user, id);
  if (!view) throw AppErrors.notFound('Worker not found');

  return res.json(view);
};

Middleware

Three small pieces, each with one purpose:

// middleware/invalidRoute.ts
// Nothing matched the request: turn it into a standard 404.
export const invalidRoute: RequestHandler = (req, _res, next) => {
  next(AppErrors.notFound(`Route not found: ${req.method} ${req.originalUrl}`));
};
// middleware/customError.ts
// Errors we threw on purpose (4xx): respond with the status & message we chose.
export const customError: ErrorRequestHandler = (err, _req, res, next) => {
  if (!createError.isHttpError(err) || err.status >= 500) return next(err);

  res.status(err.status).json({ message: err.message });
};
// middleware/unhandledError.ts
// The fallback. Anything that gets here is a real problem: log it & return a 500.
export const unhandledError: ErrorRequestHandler = (err, _req, res, _next) => {
  logger.error(err);

  res.status(500).json({ message: 'Internal Server Error' });
};

Mount point: these go at the very end of your app setup, after every router, in this order:

// app.ts
app.use('/api', apiRouter);

app.use(invalidRoute);
app.use(customError);
app.use(unhandledError);

When should you still use try/catch blocks?

  1. You're on Express 4 with async controllers
  2. You want to handle an expected error in a non-standard way
  3. Your code is outside the bounds of a request (e.g. Actions, Repositories, Services, NOT controllers, NOT middleware)

Express 4 with async controllers

Express 4 doesn't know what to do with a rejected promise. If an async handler throws, the error never reaches your error middleware: the request hangs, or worse, the unhandled rejection takes the process down. You either try/catch & call next(error), or wrap your handlers once so you never have to think about it again:

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

router.get('/profiles/:id', asyncHandler(readProfile));

Handling expected errors in a non-standard way

Sometimes one failure shouldn't fail the whole request. A bulk endpoint is the classic case: if 1 of 200 rows is bad, the caller wants to know which one, not get a 500 for the entire batch.

export const bulkUpsertEquipment = async (req: Request, res: Response) => {
  const created: string[] = [];
  const failed: string[] = [];

  await Promise.all(
    req.body.map(async (item: EquipmentRequest) => {
      try {
        await upsertEquipment(item);
        created.push(item.name);
      } catch (error) {
        logger.error(error);
        failed.push(item.name);
      }
    }),
  );

  return res.json({ created, failed });
};

The try/catch earns its place here because it's doing something the standard path can't.

Handling errors outside the scope of a request

The error middleware only exists inside the request lifecycle. Code that can run outside of it (a queue worker, a cron job, a script calling straight into your actions, repositories or services) has nothing above it to catch a thrown error, so it has to handle its own failures.


Logging Errors

Route everything through one logger instead of console.error so every error ends up in the same place with the same shape. Then be picky about what you send it:

  • Logs cost money, & they're useless if they're too noisy (log fatigue).
  • Stop catching, logging & rethrowing. You should (& we do) have a platform for catching & logging errors. Catching just to log & rethrow is an antipattern that bloats your logs with duplicates (cost & noise).
  • Only log errors for legitimate errors: things you want to be alerted on so you can take action. A useful test: "If I was called every time the error rate spiked or reached a certain threshold, what kinds of 'errors' would I NOT want to trigger this alerting system?"

Examples of things we were logging as errors that aren't really errors:

  • A user typed the wrong password (info?)
  • A message couldn't be sent because the recipient unsubscribed (warning?)
  • A frontend form was submitted with a validation issue that was only caught by the server (info?)
  • Per-record upsert issues from the public API (still an error but filtered differently, or a warning?)
  • A product analytics event failed to send (warning? different filtering?)

The question marks are intentional. The right level is a judgment call per case, but "error" should mean "someone needs to look at this."

Open Questions

  • How can we add additional metadata (e.g. toast: boolean; route: string;) to the error response payload so the client can decide how to present the error & loggers can surface the information for debugging?
  • Can we add the route to the error handling middleware so every unhandled error is logged with where it came from?