Skip to content

About

A global error handler for Node.js, on Express and Fastify.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Node.js Global Error Handler

Companion code for a post on poschuler.com. One small API, the same routes on Express 5 and on Fastify, shows what a global error handler is and how it works.

The Idea

Every error from the application leaves the API through one translation to a response:

  • Expected failures are returned. A taken email or an unknown user is a Result, and the route answers it.
  • Unexpected failures are thrown. A database that is down is caught once, by the global handler, which logs it and answers with a generic 500.

Both paths end in the same function, toProblem(). The error statuses and the response format live in one place, and the routes only name their success status. The errors are framework-agnostic, so Express and Fastify answer every case in the demo with the same status and body.

Run It

Requires Node.js v24 or higher and pnpm (the project pins pnpm@12.16.1 via the packageManager field).

git clone https://github.com/poschuler/nodejs-global-error-handler.git
cd nodejs-global-error-handler
pnpm install
pnpm demo

The demo boots both apps on free ports, sends each request to both, and exits non-zero if a status or a code is not the expected one, or if the bodies differ. requestId is left out of the comparison because it is random by design.

                          express  fastify  code
POST /users               201 ✓    201 ✓    —
POST /users (again)       409 ✓    409 ✓    User.emailTaken
GET /users/1              200 ✓    200 ✓    —
GET /users/999            404 ✓    404 ✓    User.notFound
POST /users (bad JSON)    400 ✓    400 ✓    Http.malformedJson
POST /users (no name)     422 ✓    422 ✓    Validation.invalidBody
POST /users (blank name)  422 ✓    422 ✓    User.invalidName
POST /users (bad email)   422 ✓    422 ✓    User.invalidEmail
GET /boom                 500 ✓    500 ✓    Http.unexpected
GET /nope                 404 ✓    404 ✓    Http.routeNotFound

All 10 cases match: same status, code and body on both frameworks.

For GET /boom, the demo also prints what the handler keeps. The client gets a generic body; the log gets the real error, under the same requestId.

{
  "type": "about:blank",
  "title": "Internal Server Error",
  "status": 500,
  "detail": "An unexpected error occurred.",
  "instance": "/boom",
  "code": "Http.unexpected",
  "requestId": "e48b1f5b-3651-4e50-b40f-2b8e611a6201"
}

To try the requests by hand, start both apps with pnpm start and open the files in requests/ with the REST Client extension for VS Code. Each file has the demo's cases, in order, with the expected status and code in the title. The data lives in memory, so restart the apps to start over.

The Files

Path What it holds
src/shared/ Result, the shape of an error, and the validation error
src/users/ The example module: User, Email, and the two use cases
src/http/ toProblem(), the HTTP errors, and logError(), with no framework
src/express/ The Express app and its error middleware
src/fastify/ The Fastify app and its error handlers
src/demo.ts Sends every case to both apps and compares the answers
requests/ The demo's cases as REST Client files, one per framework

Dependencies point one way, from top to bottom: express and fastify, then http, then users, then shared.

Worth a Second Look

  • RESPONSE_BY_CODE is exhaustive. It is a Record over every error code, so a code added to an error type does not compile until it has a status.
  • The 500 cannot leak. HttpErrors.unexpected() takes no arguments, so the original error has no way into the response.
  • The two handlers side by side. src/express/error-handler.ts and src/fastify/error-handler.ts have the same shape. Each recognises its framework's malformed-JSON error; only Express needs the headersSent check.
  • GET /boom is async on purpose. In Express 5 a rejected promise reaches the error middleware on its own; Express 4 needed a wrapper.
  • A domain error takes the same path. Email returns User.invalidEmail and User returns User.invalidName, and neither adapter knows they exist.

Known Limits

  • The frameworks match on the demo's cases, not everywhere. An empty body or a bare JSON value such as 123 is a 400 on one and a 422 on the other, and Express accepts a trailing slash or a different case in a path where Fastify answers 404.
  • Fastify rejects some URLs before the handler. A badly encoded URL or a very long parameter gets Fastify's own response, not Problem Details.
  • Other framework errors are not translated. A body too large or an unsupported media type can end as a 500.

Deliberately Left Out

  • Process-level handlers. unhandledRejection and uncaughtException are a different layer.
  • Graceful shutdown. Nothing here needs draining.
  • Logging and observability. logError() is a console.error; in production it would be your logger.
  • Fastify's native validation. Zod checks the shape in both frameworks, so the use case is the same.
  • Tests. pnpm demo is the check.

Commands

Command What it does
pnpm demo Runs every case on both frameworks and compares
pnpm start Starts both apps
pnpm start:express Starts the Express app on port 3001
pnpm start:fastify Starts the Fastify app on port 3002
pnpm check Format check, lint and type-check, in that order
pnpm typecheck Type-checks src without emitting
pnpm lint / pnpm lint:fix oxlint with type-aware rules, reporting or writing
pnpm format / pnpm format:check oxfmt, writing or checking

License

MIT

About

A global error handler for Node.js, on Express and Fastify.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages