Standard HTTP Error Class

2.0.1 · abandoned · verified Tue Apr 21

The `standard-http-error` package provides a minimalist, extensible JavaScript error class (`HttpError`) specifically designed for representing HTTP status codes. It allows for easy detection of HTTP-related errors using `instanceof` checks within error handling middleware. Currently at version 2.0.1, the core library has not seen updates since 2017, suggesting it is effectively abandoned by its original author, though type definitions are community-maintained. It follows semantic versioning for its major versions. Its key differentiators include its small footprint, direct alignment with standard HTTP status codes (supporting both numeric codes and descriptive names like "NOT_FOUND"), and features for proper error serialization. It offers compatibility with frameworks like Express and Koa by providing non-enumerable aliases for `code` and `message` as `status`, `statusCode`, and `statusMessage` for consistent error object structures.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating `HttpError` instances with numeric codes, named codes, custom messages, and custom properties, and catching them with `instanceof`.

import HttpError from 'standard-http-error';

try {
  // Create an HTTP error with a specific code
  throw new HttpError(404);
} catch (err) {
  if (err instanceof HttpError) {
    console.log(`Caught HttpError: ${err.name} (${err.code}) - ${err.message}`); // Output: HttpError (404) - Not Found
  }
}

try {
  // Create an HTTP error with a named code and custom message
  throw new HttpError(HttpError.FORBIDDEN, 'Access to this resource is denied');
} catch (err) {
  if (err instanceof HttpError) {
    console.log(`Caught HttpError: ${err.name} (${err.code}) - ${err.message}`); // Output: HttpError (403) - Access to this resource is denied
  }
}

try {
  // Create an HTTP error with custom properties
  throw new HttpError(412, 'Bad CSRF Token', { url: '/api/resource', userId: 'user123' });
} catch (err) {
  if (err instanceof HttpError) {
    console.log(`Caught HttpError with custom props: ${err.code} - ${err.message}. URL: ${err.url}, User: ${err.userId}`);
  }
}

view raw JSON →