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

@b9g/http-errors

v0.2.1

Published

Standard HTTP error classes with native cause support and automatic serialization

Readme

@b9g/http-errors

Standard HTTP error classes with native cause support and automatic serialization

Features

  • Universal: Works in browsers, Node.js, Bun, and edge platforms
  • Response Protocol: Implements toResponse() for automatic HTTP response conversion
  • Structured Logging: Built-in toJSON() for clean error serialization
  • Standard HTTP Status Codes: Pre-defined classes for all common HTTP errors
  • TypeScript Support: Full type definitions for all error classes
  • Error Chaining: Native cause support for error context

Installation

npm install @b9g/http-errors

Quick Start

import {
  NotFound,
  BadRequest,
  Unauthorized,
  InternalServerError
} from '@b9g/http-errors';

// Throw as exceptions
throw new NotFound('Page not found');
throw new BadRequest('Invalid input data');

// Or convert to Response objects
const error = new NotFound('Page not found');
return error.toResponse(); // Response with status 404

// In development, get detailed error pages
return error.toResponse(true); // HTML page with stack trace

API

HTTPError Class

Base class for all HTTP errors. Extends Error.

import { HTTPError } from '@b9g/http-errors';

const error = new HTTPError(404, 'Resource not found', {
  cause: originalError,        // Error that caused this
  headers: {                    // Custom headers for response
    'Cache-Control': 'no-store'
  },
  expose: true                  // Whether to expose message to client
});

error.status;        // 404
error.message;       // 'Resource not found'
error.expose;        // true (client errors default to true, server errors to false)
error.headers;       // { 'Cache-Control': 'no-store' }

Methods

toResponse(isDev?: boolean): Response

Converts the error to an HTTP Response object.

  • In development mode (isDev = true): Returns HTML page with stack trace
  • In production mode: Returns plain text with minimal information
const error = new NotFound('Page not found');

// Production response
error.toResponse();      // Response { status: 404, body: 'Page not found' }

// Development response with stack trace
error.toResponse(true);  // Response { status: 404, body: '<html>...</html>' }

toJSON(): object

Converts the error to a plain object for logging and serialization.

const error = new BadRequest('Invalid email', {
  headers: { 'X-Custom': 'value' }
});

JSON.stringify(error);
// {
//   "name": "BadRequest",
//   "message": "Invalid email",
//   "status": 400,
//   "statusCode": 400,
//   "expose": true,
//   "headers": { "X-Custom": "value" }
// }

### Client Error Classes (4xx)

```javascript
import {
  BadRequest,           // 400
  Unauthorized,         // 401
  Forbidden,            // 403
  NotFound,             // 404
  MethodNotAllowed,     // 405
  Conflict,             // 409
  UnprocessableEntity,  // 422
  TooManyRequests       // 429
} from '@b9g/http-errors';

// All accept message and options
throw new Unauthorized('Invalid credentials', {
  headers: { 'WWW-Authenticate': 'Bearer realm="api"' }
});

throw new TooManyRequests('Rate limit exceeded', {
  headers: { 'Retry-After': '60' }
});

Server Error Classes (5xx)

import {
  InternalServerError,  // 500
  NotImplemented,       // 501
  BadGateway,           // 502
  ServiceUnavailable,   // 503
  GatewayTimeout        // 504
} from '@b9g/http-errors';

// Server errors default to expose: false
throw new InternalServerError('Database connection failed', {
  cause: dbError  // Chain the original error
});

Functions

isHTTPError(value): value is HTTPError

Type guard to check if a value is an HTTPError.

import {isHTTPError} from '@b9g/http-errors';

try {
  // ...
} catch (err) {
  if (isHTTPError(err)) {
    return err.toResponse();
  }
  throw err;
}

Types

interface HTTPErrorOptions {
  /** Original error that caused this HTTP error */
  cause?: Error;
  /** Custom headers to include in the error response */
  headers?: Record<string, string>;
  /** Whether error details should be exposed to clients (defaults based on status) */
  expose?: boolean;
  /** Additional properties to attach to the error */
  [key: string]: any;
}

License

MIT