npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@prefabs.tech/fastify-error-handler

v0.94.1

Published

Fastify error-handler plugin

Downloads

1,641

Readme

@prefabs.tech/fastify-error-handler

A Fastify plugin that provides a standardized, production-safe global error handler for APIs.

Why This Plugin?

In a large API or microservice ecosystem, inconsistent error handling quickly leads to bloated controllers and unpredictable API responses for your frontend clients. We created this plugin to:

  • Unify Your Error Responses: By providing a global error formatter powered by @fastify/sensible, we ensure that no matter where an error originates — a database crash, a validation failure, or a manual throw — your API always responds with a standardized, predictable JSON shape.
  • Keep Controllers Clean: We enforce an exceptions-based approach. Focus purely on the happy path in your route handlers. Instead of manually catching errors and calling reply.code(400).send(...), you simply throw an error and let the global handler manage the rest.
  • Provide Safe Interception: Fastify only allows one global setErrorHandler. If you use libraries like SuperTokens that require their own error handling, standard setups break. We designed a clean preErrorHandler option to let you safely run those third-party hooks before falling back to the standard global formatter.
  • Standardize Custom Exceptions: We provide a strongly-typed CustomError base class so you can attach specific application error codes and metadata across your monorepo without resorting to raw strings or plain Error objects.

What You Get

@fastify/sensible — Full Passthrough

All options from @fastify/sensible are supported. This plugin registers it internally with no configuration, exposing fastify.httpErrors.* helpers on the instance.

Added by This Plugin

  • Global error handler — catches all thrown errors (HttpErrors, CustomErrors, plain Errors, and non-Error values) and formats them into a consistent ErrorResponse JSON shape
  • Safe message masking — 5xx errors hide implementation details behind generic messages by default; stackTrace: true disables masking for development
  • preErrorHandler hook — run custom logic (e.g. SuperTokens, Passport) before the default handler; short-circuits if your handler sends the reply, swallows exceptions otherwise
  • CustomError base class — extend it to create domain errors with a custom code field; subclasses are handled safely
  • stackTrace option — controls whether parsed stack frames are included in error responses
  • ErrorResponse JSON schema — registered as $id: "ErrorResponse" for use in route response schemas via $ref: "ErrorResponse#"
  • Severity-aware logging — 4xx errors log at info, 5xx at error; non-Error thrown values are normalized and logged safely
  • domainErrorStatusMap — optional app-provided Map<string, number> from error.name to an HTTP status integer 400599 (invalid entries fail at registration); the plugin stores a validated copy. Mapped errors return that status with message/name (and CustomError code) in the body—only unmapped non-HttpError errors use generic masking when stackTrace is false

Full feature list · Developer guide

Usage Guidelines

Controllers must not reply with non-200 responses

Do not manually send error responses from route handlers. Always throw and let the global error handler format the response.

Wrong

fastify.get("/test", async (req, reply) => {
  return reply.code(401).send({ message: "Unauthorized" });
});

Correct

fastify.get("/test", async () => {
  throw fastify.httpErrors.unauthorized("Unauthorized");
});

Throw CustomError (or a subclass) for domain errors

Modules must throw an instance of CustomError (or a class extending it) for application-level errors. This ensures errors are caught consistently and the correct action can be taken.

import { CustomError } from "@prefabs.tech/fastify-error-handler";

const file = await fileService.findById(id);
if (!file) {
  throw new CustomError("File not found", "FILE_NOT_FOUND_ERROR");
}

Requirements

Peer dependencies (must be installed separately):

Register this plugin before all routes and other plugins so the error handler is in place for the entire application.

Quick Start

import errorHandlerPlugin from "@prefabs.tech/fastify-error-handler";
import Fastify from "fastify";

const fastify = Fastify();

await fastify.register(errorHandlerPlugin, {
  stackTrace: process.env.NODE_ENV === "development",
});

// Throw errors in routes — the handler does the rest
fastify.get("/example", async () => {
  throw fastify.httpErrors.notFound("Resource not found");
});

await fastify.listen({ port: 3000, host: "0.0.0.0" });

Domain status codes

Use domainErrorStatusMap when domain errors should return non-500 statuses — pass a Map whose keys match thrown error.name; each value must be an integer 400599. Mapped responses include the thrown message and name (and CustomError codes); generic masking applies only to unmapped internal errors when stackTrace is off.

await fastify.register(errorHandlerPlugin, {
  domainErrorStatusMap: new Map([["UnprocessableEntityError", 422]]),
});

Standalone errorHandler usage

If you use the exported errorHandler directly (without registering the plugin), pass options as the 4th argument:

import { errorHandler } from "@prefabs.tech/fastify-error-handler";

fastify.setErrorHandler((error, request, reply) => {
  return errorHandler(error, request, reply, {
    stackTrace: true,
    domainErrorStatusMap: new Map([["UnprocessableEntityError", 422]]),
  });
});

Installation

Install with npm:

npm install @prefabs.tech/fastify-error-handler

Install with pnpm:

pnpm add @prefabs.tech/fastify-error-handler