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

exception-handler-express

v1.1.0

Published

A robust, extensible exception handling library for Node.js and Express. Provides typed HTTP exceptions, automatic error formatting, and optional Sentry integration out of the box.

Readme

exception-handler-express

npm version license downloads

A robust, extensible exception handling library for Node.js and Express. Provides typed HTTP exception classes, automatic error formatting, and optional Sentry integration out of the box.


Features

  • 🎯 Typed HTTP ExceptionsBadRequest, NotFound, Unauthorized, Forbidden, Conflict, and many more
  • 🛡️ Express Error Middleware — Drop-in middleware that catches errors, formats responses, and reports to Sentry
  • 📡 Sentry Integration — Optional built-in Sentry error reporting with breadcrumb filtering and header sanitization
  • 🔌 Extensible — Bring your own error reporter by implementing IErrorReporter
  • 🧩 Dual Module — Ships both ESM and CommonJS builds with full TypeScript declarations
  • Axios Support — Automatically wraps AxiosError responses into structured API errors

Installation

npm install exception-handler-express

Peer Dependencies

The following are optional peer dependencies — install only what you need:

# Required if using the ExceptionHandler middleware
npm install express

# Required if using the built-in Sentry reporter
npm install @sentry/node

# Required if using ApiError / Axios error wrapping
npm install axios

Quick Start

1. Throw Typed Exceptions

import { Exceptions } from 'exception-handler-express';

// In your route handler
app.get('/users/:id', async (req, res) => {
  const user = await findUser(req.params.id);

  if (!user) {
    throw new Exceptions.NotFound('User not found');
  }

  // With custom error code and metadata
  if (!user.isActive) {
    throw new Exceptions.Forbidden('Account suspended', {
      errorCode: 'ACCOUNT_SUSPENDED',
      data: { userId: user.id },
    });
  }

  res.json(user);
});

2. Add the Error Middleware

import express from 'express';
import { ExceptionHandler } from 'exception-handler-express';

const app = express();

// ... your routes ...

// Add as the LAST middleware (after all routes)
app.use(ExceptionHandler.middleware());

3. Enable Sentry Reporting (Optional)

import { ExceptionHandler, SentryReporterFactory } from 'exception-handler-express';

// Option A: Auto-configure via environment variable
// Set SENTRY_DSN in your env, and the middleware picks it up automatically
app.use(ExceptionHandler.middleware());

// Option B: Explicit configuration
const reporter = SentryReporterFactory.createInstance({
  dsn: 'https://your-sentry-dsn',
});

app.use(ExceptionHandler.middleware(false, reporter));

API Reference

Exception Classes

All exceptions extend BaseException and include an HTTP status code, error code, and optional metadata.

| Exception | Status Code | Default Error Code | | ----------------------- | ----------- | ------------------------ | | BadRequest | 400 | BAD_REQUEST | | Unauthorized | 401 | UNAUTHORIZED | | Forbidden | 403 | FORBIDDEN | | NotFound | 404 | NOT_FOUND | | MethodNotAllowed | 405 | METHOD_NOT_ALLOWED | | NotAcceptable | 406 | NOT_ACCEPTABLE | | RequestTimeout | 408 | REQUEST_TIMEOUT | | Conflict | 409 | CONFLICT | | PayloadTooLarge | 413 | PAYLOAD_TOO_LARGE | | UnsupportedMediaType | 415 | UNSUPPORTED_MEDIA_TYPE | | TooManyRequests | 429 | TOO_MANY_REQUESTS | | InternalServerError | 500 | INTERNAL_SERVER_ERROR | | NotImplemented | 501 | NOT_IMPLEMENTED | | BadGateway | 502 | BAD_GATEWAY | | ServiceUnavailable | 503 | SERVICE_UNAVAILABLE | | ApiError | varies | from Axios response |

Constructor

new BadRequest(message: string, metaData?: IErrorMetaData)
  • message — Human-readable error message
  • metaData.errorCode — Override the default error code string
  • metaData.data — Attach arbitrary data to the error response

Error Response Format

{
  "code": "NOT_FOUND",
  "message": "User not found",
  "traceId": "a1b2c3d4-...",
  "data": {}
}

In non-production environments (NODE_ENV !== 'production'), stack traces and error names are included in data.


ExceptionHandler.middleware(showStackTrace?, reporter?)

Express error-handling middleware.

| Parameter | Type | Default | Description | | ---------------- | ----------------- | ----------------------------- | ------------------------------------------------ | | showStackTrace | boolean | false | Force stack traces in responses | | reporter | IErrorReporter | Sentry (if SENTRY_DSN set) | Custom error reporter instance |

Behaviour:

  • Catches BaseException instances and formats them into JSON responses
  • Wraps AxiosError instances into ApiError
  • Wraps unknown errors into InternalServerError
  • Reports 5xx errors to the configured reporter (if any)
  • Attaches a unique traceId to every error response

SentryReporterFactory

Factory for creating Sentry reporter instances.

// Auto-detect from SENTRY_DSN env var
const reporter = SentryReporterFactory.getInstance();

// Explicit configuration
const reporter = SentryReporterFactory.createInstance({
  dsn: 'https://...',
  filterBreadcrumbs: (breadcrumb) => breadcrumb,
  beforeReport: (event) => event,
});

Custom Error Reporter

Implement the IErrorReporter interface to use your own reporting service:

import { IErrorReporter, IErrorReportScopes } from 'exception-handler-express';

class CustomReporter implements IErrorReporter {
  reportEvent(event: Object, scopes?: IErrorReportScopes): void {
    // Send to your monitoring service
  }

  reportMessage(message: string, scopes?: IErrorReportScopes): void {
    // Send to your monitoring service
  }

  reportException(error: Error | unknown, scopes?: IErrorReportScopes): void {
    // Send to your monitoring service
  }
}

app.use(ExceptionHandler.middleware(false, new CustomReporter()));

Enums

HttpStatusCode

Standard HTTP status codes (100–505).

HttpErrorCode

String error code identifiers matching the exception classes.


Exports

import {
  // Exception classes (namespaced)
  Exceptions,

  // Middleware
  ExceptionHandler,

  // Sentry integration
  SentryReporterFactory,

  // Enums
  HttpStatusCode,
  HttpErrorCode,

  // Types
  IErrorReporterOptions,
} from '@automatonatm/exceptionhandler';

// Access individual exceptions
const { BadRequest, NotFound, Unauthorized } = Exceptions;

Environment Variables

| Variable | Description | Required | | ----------------- | ------------------------------------ | -------- | | NODE_ENV | Controls stack trace visibility | No | | SENTRY_DSN | Auto-enables Sentry reporting | No | | SENTRY_RELEASE | Sets the Sentry release tag | No |


License

MIT