Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Error handler

Validated

Classify errors, hide internal details, and return one response shape in Express, Fastify, and Hono.

The error handler block converts thrown values into a client-safe response. It classifies the error, redacts sensitive fields, logs or reports the event, and returns a status code plus a stable JSON envelope.

The core is framework-agnostic. Create one boundary and pass it to the adapter for your framework.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add error-handler
import express from "express";
import { AppError, createErrorBoundary } from "@/blocks/error-handler";
import { createExpressErrorHandler } from "@/blocks/error-handler/adapters/express";

const app = express();
const boundary = createErrorBoundary();

app.get("/users/:id", async (req, res) => {
  const user = await db.user.findUnique({ where: { id: req.params.id } });

  if (!user) {
    throw new AppError({
      code: "USER_NOT_FOUND",
      message: "User not found",
      category: "NOT_FOUND"
    });
  }

  res.json(user);
});

app.use(createExpressErrorHandler(boundary));

createExpressErrorHandler returns Express error middleware. Register it after your routes. It needs the boundary argument.

Files

error-handler/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── core/
│   ├── app-error.ts
│   ├── classify.ts
│   ├── context.ts
│   ├── create-error-boundary.ts
│   ├── defaults.ts
│   ├── normalize.ts
│   ├── sanitize.ts
│   └── serialize.ts
├── express/
│   ├── async-handler.ts
│   ├── errors.ts
│   ├── global-error-handler.ts
│   ├── http-status.ts
│   ├── index.ts
│   └── throw-error.ts
├── types/
└── index.ts

The root index.ts exports AppError, createErrorBoundary, the sanitizer, the serializer, and the public types. Adapters are separate modules. The express/ folder is a deprecated compatibility layer for older imports.

Installation

pnpm dlx blockend-cli add error-handler

The CLI copies the core, one framework adapter, and the tests. No runtime dependencies beyond the framework you already use.

Copy index.ts, core/, types/, and one adapter. Keep the relative layout.

Root exports

export { AppError } from "./core/app-error";
export { createErrorBoundary } from "./core/create-error-boundary";
export { DEFAULT_SENSITIVE_KEYS, sanitizeErrorData } from "./core/sanitize";
export { serializeErrorResponse } from "./core/serialize";
export type {
  AppErrorOptions,
  ClassifiedError,
  CreateErrorBoundaryOptions,
  ErrorBoundary,
  ErrorBoundaryResult,
  ErrorCategory,
  ErrorClassifier,
  ErrorContext,
  ErrorContextInput,
  ErrorEvent,
  ErrorLogger,
  ErrorReporter,
  ErrorResponse,
  ErrorSerializer,
  ErrorSeverity
} from "./types/index";

Boundary

import type {
  ClassifiedError,
  CreateErrorBoundaryOptions,
  ErrorBoundary,
  ErrorContext,
  ErrorEvent
} from "../types/index";
import { classifyError } from "./classify";
import { enrichErrorContext } from "./context";
import { normalizeError } from "./normalize";
import { sanitizeErrorData } from "./sanitize";
import { serializeErrorResponse } from "./serialize";

/** Builds the sanitized event shape shared by logging and reporting hooks. */
function createEvent(error: ClassifiedError, context: ErrorContext): ErrorEvent {
  return {
    error: {
      name: error.name,
      code: error.code,
      message: error.message,
      statusCode: error.statusCode,
      category: error.category,
      severity: error.severity,
      isOperational: error.isOperational,
      ...(error.stack === undefined ? {} : { stack: error.stack }),
      ...(error.cause === undefined ? {} : { cause: error.cause }),
      ...(error.metadata === undefined ? {} : { metadata: error.metadata })
    },
    context
  };
}

/** Create a framework-agnostic error boundary with optional logger, reporter, and classifier. */
export function createErrorBoundary(options: CreateErrorBoundaryOptions = {}): ErrorBoundary {
  const serializer = options.serializer ?? serializeErrorResponse;
  const sensitiveKeys = options.sensitiveKeys ?? [];

  return {
    async handle(error, contextInput = {}) {
      const normalized = normalizeError(error);
      const classified = classifyError(normalized, options.classifier);
      const context = sanitizeErrorData(enrichErrorContext(contextInput), sensitiveKeys);
      const safeError = sanitizeErrorData(classified, sensitiveKeys);
      const event = sanitizeErrorData(createEvent(safeError, context), sensitiveKeys);

      if (options.logger) {
        try {
          options.logger.error(event as unknown as Record<string, unknown>, "Application error");
        } catch {
          // Logging must not change the response path.
        }
      }

      if (options.reporter) {
        try {
          await options.reporter.report(event);
        } catch {
          // Reporting must not replace the application error.
        }
      }

      let body;
      try {
        body = serializer(safeError, context);
      } catch {
        body = serializeErrorResponse(safeError, context);
      }

      return {
        statusCode: safeError.isOperational ? safeError.statusCode : 500,
        body
      };
    }
  };
}

AppError

import type { AppErrorOptions, ErrorCategory, ErrorSeverity } from "../types/index";
import { inferCategory, inferSeverity, resolveStatusCode } from "./defaults";

/** Typed error carrying status, category, and operational metadata. */
export class AppError extends Error {
  readonly code: string;
  readonly statusCode: number;
  readonly category: ErrorCategory;
  readonly severity: ErrorSeverity;
  readonly isOperational: boolean;
  readonly metadata?: Record<string, unknown>;
  readonly details?: unknown;

  constructor(options: AppErrorOptions);
  /** @deprecated Use the options-object constructor. */
  constructor(statusCode: number, message: string, isOperational?: boolean);
  constructor(
    optionsOrStatusCode: AppErrorOptions | number,
    legacyMessage?: string,
    legacyIsOperational?: boolean
  ) {
    const options: AppErrorOptions =
      typeof optionsOrStatusCode === "number"
        ? {
            code: "APP_ERROR",
            message: legacyMessage ?? "Application error",
            statusCode: optionsOrStatusCode,
            ...(legacyIsOperational === undefined ? {} : { isOperational: legacyIsOperational })
          }
        : optionsOrStatusCode;

    super(options.message, options.cause === undefined ? undefined : { cause: options.cause });

    const statusCode = resolveStatusCode(options.statusCode, options.category);
    this.name = "AppError";
    this.code = options.code;
    this.statusCode = statusCode;
    this.category = options.category ?? inferCategory(statusCode);
    this.severity = options.severity ?? inferSeverity(statusCode);
    this.isOperational = options.isOperational ?? statusCode < 500;
    if (options.metadata !== undefined) this.metadata = options.metadata;
    if (options.details !== undefined) this.details = options.details;
    Object.setPrototypeOf(this, AppError.prototype);
  }
}

Sanitizer

/** Built-in case-insensitive key fragments redacted by the sanitizer. */
export const DEFAULT_SENSITIVE_KEYS = [
  "password",
  "passphrase",
  "token",
  "authorization",
  "secret",
  "apikey",
  "cookie"
] as const;

const REDACTED = "[REDACTED]";
const CIRCULAR = "[Circular]";
const TRUNCATED = "[Truncated]";

/** Normalizes object keys for case- and punctuation-insensitive sensitivity checks. */
function normalizeKey(key: string): string {
  return key.toLowerCase().replace(/[^a-z0-9]/g, "");
}

/** Deep-clone and redact sensitive keys, circular references, and unserializable values. */
export function sanitizeErrorData<T>(value: T, additionalKeys: readonly string[] = []): T {
  const sensitiveKeys = [...DEFAULT_SENSITIVE_KEYS, ...additionalKeys].map(normalizeKey);
  const seen = new WeakSet<object>();

  const visit = (current: unknown, depth: number): unknown => {
    if (current === null || current === undefined) return current;
    if (typeof current === "bigint") return current.toString();
    if (typeof current === "symbol") return current.toString();
    if (typeof current === "function") return "[Function]";
    if (typeof current !== "object") return current;
    if (depth >= 8) return TRUNCATED;
    if (seen.has(current)) return CIRCULAR;

    seen.add(current);

    if (current instanceof Date) {
      let result: unknown;
      try {
        result = current.toISOString();
      } catch {
        result = "[Unserializable]";
      }
      seen.delete(current);
      return result;
    }
    if (current instanceof Error) {
      const result = visit(
        {
          name: current.name,
          message: current.message,
          ...(current.stack === undefined ? {} : { stack: current.stack }),
          ...(current.cause === undefined ? {} : { cause: current.cause })
        },
        depth + 1
      );
      seen.delete(current);
      return result;
    }
    if (Array.isArray(current)) {
      const result = current.map((entry) => visit(entry, depth + 1));
      seen.delete(current);
      return result;
    }

    const sanitized: Record<string, unknown> = {};
    let entries: [string, unknown][];
    try {
      entries = Object.entries(current);
    } catch {
      seen.delete(current);
      return "[Unserializable]";
    }

    for (const [key, entry] of entries) {
      const normalized = normalizeKey(key);
      sanitized[key] = sensitiveKeys.some((sensitive) => normalized.includes(sensitive))
        ? REDACTED
        : visit(entry, depth + 1);
    }
    seen.delete(current);
    return sanitized;
  };

  return visit(value, 0) as T;
}

Serializer

import type { ErrorSerializer } from "../types/index";
import { INTERNAL_ERROR_MESSAGE } from "./defaults";

/** Default serializer that produces a safe client envelope; hides internal error details. */
export const serializeErrorResponse: ErrorSerializer = (error, context) => {
  const message = error.isOperational ? error.message : INTERNAL_ERROR_MESSAGE;
  const details = error.isOperational ? error.details : undefined;
  return {
    success: false,
    data: null,
    error: { message, ...(details === undefined ? {} : { details }) },
    ...(context.requestId === undefined ? {} : { requestId: context.requestId })
  };
};

Express adapter

import type { NextFunction, Request, Response } from "express";
import type { ErrorBoundary, ErrorContextInput } from "../types/index";

interface RequestWithId extends Request {
  id?: string;
}

/** Options for the Express error handler adapter. */
export interface ExpressErrorHandlerOptions {
  getContext?: (request: Request) => ErrorContextInput;
}

/** Extracts the standard error context available on an Express request. */
function defaultContext(request: RequestWithId): ErrorContextInput {
  const header = request.headers["x-request-id"];
  const headerId = Array.isArray(header) ? header[0] : header;
  return {
    method: request.method,
    path: request.path,
    ...(request.id ? { requestId: request.id } : headerId ? { requestId: headerId } : {})
  };
}

/** Create an Express error-handler middleware backed by an {@link ErrorBoundary}. */
export function createExpressErrorHandler(
  boundary: ErrorBoundary,
  options: ExpressErrorHandlerOptions = {}
) {
  return async (
    error: unknown,
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> => {
    if (response.headersSent) {
      next(error);
      return;
    }
    const context = { ...defaultContext(request), ...options.getContext?.(request) };
    const result = await boundary.handle(error, context);
    response.status(result.statusCode).json(result.body);
  };
}

Fastify adapter

import type { FastifyInstance, FastifyRequest } from "fastify";
import type { ErrorBoundary, ErrorContextInput } from "../types/index";

/** Options for the Fastify error handler adapter. */
export interface FastifyErrorHandlerOptions {
  getContext?: (request: FastifyRequest) => ErrorContextInput;
}

/** Register a Fastify error handler backed by an {@link ErrorBoundary}. */
export function registerFastifyErrorHandler(
  app: FastifyInstance,
  boundary: ErrorBoundary,
  options: FastifyErrorHandlerOptions = {}
): void {
  app.setErrorHandler(async (error, request, reply) => {
    const customContext = options.getContext?.(request);

    const context = {
      ...customContext,
      requestId: request.id,
      method: request.method,
      path: (request.url ?? "").split("?")[0] ?? ""
    };

    const result = await boundary.handle(error, context);

    return reply.status(result.statusCode).send(result.body);
  });
}

Hono adapter

import type { Context, Env, ErrorHandler, Hono } from "hono";
import type { ContentfulStatusCode } from "hono/utils/http-status";
import type { ErrorBoundary, ErrorContextInput } from "../types/index";

/** Options for the Hono error handler adapter. */
export interface HonoErrorHandlerOptions<E extends Env = Env> {
  getContext?: (context: Context<E>) => ErrorContextInput;
}

/** Reads a request ID from Hono variables or the incoming request header. */
function requestIdFromContext<E extends Env>(context: Context<E>): string | undefined {
  const contextId = (context.var as Record<string, unknown>).requestId;
  if (typeof contextId === "string") return contextId;
  return context.req.header("x-request-id");
}

/** Create a Hono ErrorHandler function backed by an {@link ErrorBoundary}. */
export function createHonoErrorHandler<E extends Env = Env>(
  boundary: ErrorBoundary,
  options: HonoErrorHandlerOptions<E> = {}
): ErrorHandler<E> {
  return async (error, context) => {
    const requestId = requestIdFromContext(context);
    const errorContext = {
      method: context.req.method,
      path: context.req.path,
      ...(requestId === undefined ? {} : { requestId }),
      ...options.getContext?.(context)
    };
    const result = await boundary.handle(error, errorContext);
    return context.json(result.body, result.statusCode as ContentfulStatusCode);
  };
}

/** Convenience helper that registers the error handler on a Hono instance. */
export function registerHonoErrorHandler<E extends Env>(
  app: Hono<E>,
  boundary: ErrorBoundary,
  options: HonoErrorHandlerOptions<E> = {}
): void {
  app.onError(createHonoErrorHandler(boundary, options));
}

Usage

Express

import express from "express";
import { AppError, createErrorBoundary } from "@/blocks/error-handler";
import { createExpressErrorHandler } from "@/blocks/error-handler/adapters/express";

const app = express();
const boundary = createErrorBoundary();

app.get("/invoices/:id", async (req, res) => {
  const invoice = await db.invoice.findUnique({ where: { id: req.params.id } });

  if (!invoice) {
    throw new AppError({
      code: "INVOICE_NOT_FOUND",
      message: "Invoice not found",
      category: "NOT_FOUND"
    });
  }

  res.json(invoice);
});

app.use(
  createExpressErrorHandler(boundary, {
    getContext: (req) => ({
      userId: req.user?.id
    })
  })
);

The examples assume your auth middleware declares req.user and request.user on the framework request types. If headersSent is already true, the adapter calls next(error) instead of writing a second response.

Fastify

import Fastify from "fastify";
import { createErrorBoundary } from "@/blocks/error-handler";
import { registerFastifyErrorHandler } from "@/blocks/error-handler/adapters/fastify";

const app = Fastify();
const boundary = createErrorBoundary();

registerFastifyErrorHandler(app, boundary, {
  getContext: (request) => ({
    userId: request.user?.id
  })
});

app.get("/invoices/:id", async (request) => {
  return db.invoice.findUniqueOrThrow({ where: { id: request.params.id } });
});

await app.listen({ port: 3000 });

The adapter sets Fastify's error handler and returns the serialized result.

Hono

import { Hono } from "hono";
import { AppError, createErrorBoundary } from "@/blocks/error-handler";
import { registerHonoErrorHandler } from "@/blocks/error-handler/adapters/hono";

const app = new Hono();
const boundary = createErrorBoundary();

registerHonoErrorHandler(app, boundary);

app.get("/invoices/:id", async (c) => {
  const invoice = await db.invoice.findUnique({ where: { id: c.req.param("id") } });

  if (!invoice) {
    throw new AppError({
      code: "INVOICE_NOT_FOUND",
      message: "Invoice not found",
      category: "NOT_FOUND"
    });
  }

  return c.json(invoice);
});

export default app;

You can also use createHonoErrorHandler(boundary) and pass it to app.onError() yourself.

AppError

Use AppError for errors you expect. The options object is required unless you are using the deprecated positional constructor.

throw new AppError({
  code: "PAYMENT_DECLINED",
  message: "The card was declined",
  statusCode: 402,
  category: "BAD_REQUEST",
  severity: "warning",
  isOperational: true,
  details: { reason: "insufficient_funds" }
});
OptionTypeDefault
codestringRequired
messagestringRequired
statusCodenumberDerived from category, otherwise 500
categoryErrorCategoryInferred from statusCode
severity"info" | "warning" | "error" | "critical"warning for 4xx, error for 5xx
isOperationalbooleantrue when statusCode < 500
causeunknownNone
metadataRecord<string, unknown>None. Never sent to the client.
detailsunknownNone. Sent only when isOperational is true.

Categories map to status codes when you do not set one:

CategoryStatus
BAD_REQUEST400
VALIDATION400
AUTHENTICATION401
AUTHORIZATION403
NOT_FOUND404
CONFLICT409
RATE_LIMIT429
INTERNAL500
SERVICE_UNAVAILABLE503

Only AppError instances and errors returned by your classifier can be operational. An arbitrary Error with a statusCode property is still treated as non-operational and returns 500.

Boundary configuration

const boundary = createErrorBoundary({
  logger,
  reporter,
  classifier,
  serializer,
  sensitiveKeys: ["privateKey", "sessionId"]
});
OptionDescription
loggerObject with error(context, message). Logger failures are ignored.
reporterObject with report(event). Reporter failures are ignored.
classifierMaps an unknown error to AppErrorOptions or null.
serializerBuilds the response body. Defaults to serializeErrorResponse.
sensitiveKeysExtra key fragments to redact. Matching is case-insensitive.

Classifier

Use a classifier for validation libraries and third-party errors:

import { z, ZodError } from "zod";

const boundary = createErrorBoundary({
  classifier(error) {
    if (!(error instanceof ZodError)) return null;

    return {
      code: "VALIDATION_FAILED",
      message: "Validation failed",
      statusCode: 400,
      category: "VALIDATION",
      details: z.treeifyError(error)
    };
  }
});

If the classifier throws, the boundary falls back to the default classification.

Logging and reporting

const boundary = createErrorBoundary({
  logger: {
    error(event, message) {
      logger.error(event, message);
    }
  },
  reporter: {
    async report(event) {
      await errorQueue.publish(event);
    }
  }
});

The event contains the sanitized error and context. The logger is called with the event object first, then the message "Application error".

Sensitive data

The default redaction list covers:

  • password
  • passphrase
  • token
  • authorization
  • secret
  • apikey
  • cookie

Matching is case-insensitive and ignores punctuation. Add your own fragments with sensitiveKeys. The sanitizer replaces circular references and functions, stringifies bigints and symbols, and truncates data beyond eight levels.

Redaction happens before logging, reporting, and serialization. metadata is for server-side diagnostics and is never included in the default client response.

Adapters

Express

createExpressErrorHandler(boundary, {
  getContext?: (request) => ErrorContextInput
});

Default context: method, path, and requestId from request.id or x-request-id.

Fastify

registerFastifyErrorHandler(app, boundary, {
  getContext?: (request) => ErrorContextInput
});

Default context: method, path without the query string, and request.id.

Hono

createHonoErrorHandler(boundary, {
  getContext?: (context) => ErrorContextInput
});

registerHonoErrorHandler(app, boundary, options?);

Default context: method, path, and requestId from the requestId variable or x-request-id.

Response shape

The default serializer returns:

{
  "success": false,
  "data": null,
  "error": {
    "message": "User not found",
    "details": {}
  },
  "requestId": "req_123"
}

details and requestId are omitted when they are not present. Non-operational errors always return status 500 and the message "Internal server error", even if the original error message was more specific.

Compatibility layer

The express/ folder exists for code written against older versions:

import {
  asyncHandler,
  ERRORS,
  globalErrorHandler,
  HTTP_STATUS,
  throwError
} from "@/blocks/error-handler/express";

globalErrorHandler is a prebuilt Express middleware with a boundary, a console logger, and a Zod classifier. It is deprecated. New code should create a boundary and pass it to createExpressErrorHandler.

API reference

createErrorBoundary

function createErrorBoundary(options?: CreateErrorBoundaryOptions): ErrorBoundary;

interface ErrorBoundary {
  handle(
    error: unknown,
    context?: ErrorContextInput
  ): Promise<{
    statusCode: number;
    body: ErrorResponse;
  }>;
}

serializeErrorResponse

function serializeErrorResponse(error: ClassifiedError, context: ErrorContext): ErrorResponse;

sanitizeErrorData

function sanitizeErrorData<T>(value: T, additionalKeys?: readonly string[]): T;

DEFAULT_SENSITIVE_KEYS

const DEFAULT_SENSITIVE_KEYS: readonly string[];

When not to use it

  • You already have a framework-wide error pipeline with the same envelope and redaction rules.
  • You need error tracking only. Use a dedicated error tracker and keep your existing responses.
  • You need to expose stack traces to clients. This block intentionally hides them.
  • Logger provides the structured logger passed to the boundary.
  • Response formatter uses the same { success, data, error } envelope.
  • Idempotency produces its own errors and status mapping.

On this page