Specialized error class for HTTP request failures

HttpError is a custom error class that is thrown when an HTTP request fails and receives an error response from a remote server. Unlike the standard Error class, it carries detailed HTTP-specific information (method, path, status code, headers) that enables more sophisticated error handling and debugging in HTTP communication scenarios.

This class is particularly useful for:

  • API client libraries that need to provide detailed error information
  • Applications that require different handling based on HTTP status codes
  • Logging and monitoring systems that need structured error data
  • Debugging HTTP communication issues

Jeongho Nam - https://github.com/samchon

Hierarchy

  • Error
    • HttpError

Constructors

  • Creates a new HttpError instance

    Initializes an HttpError with comprehensive information about the failed HTTP request. This constructor calls the parent Error constructor to set the basic error message, and additionally stores HTTP-specific details as readonly properties for later access.

    Parameters

    • method: "HEAD" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE"

      The HTTP method that was used for the request (GET, POST, PUT, DELETE, PATCH, HEAD)

    • path: string

      The path or URL that was requested (e.g., '/api/users' or 'https://api.example.com/users')

    • status: number

      The HTTP status code returned by the server (e.g., 404, 500, 401)

    • headers: Record<string, string | string[]>

      The HTTP response headers returned by the server as key-value pairs

    • message: string

      The error message from the server (typically the response body text)

    Returns HttpError

      const error = new HttpError(
    'POST',
    '/api/login',
    401,
    { 'content-type': 'application/json', 'www-authenticate': 'Bearer' },
    '{"error": "Invalid credentials", "code": "AUTH_FAILED"}'
    );
    console.log(error.status); // 401
    console.log(error.method); // "POST"

Properties

headers: Record<string, string | string[]>

The HTTP response headers returned by the server as key-value pairs

message: string
method: "HEAD" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE"

The HTTP method that was used for the failed request

name: string
path: string

The path or URL that was requested

stack?: string
status: number

The HTTP status code returned by the server

stackTraceLimit: number

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

Methods

  • Serializes the HttpError instance to a JSON-compatible object

    This method serves two primary purposes:

    1. Automatic serialization: When JSON.stringify() is called on an HttpError, this method is automatically invoked to provide a clean JSON representation
    2. Structured error data: When the server response body contains JSON, this method parses it and provides structured access to error details

    The method implements lazy parsing for the response message:

    • JSON parsing is attempted only on the first call to avoid unnecessary processing
    • Successful parsing results are cached for subsequent calls
    • If JSON parsing fails (e.g., for HTML error pages or plain text), the original string is preserved and returned as-is

    Type Parameters

    • T

      The expected type of the response body (defaults to any for flexibility)

    Returns HttpError.IProps<T>

    A structured object containing all HTTP error information with the message field containing either the parsed JSON object or the original string

  • Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

    const myObject = {};
    Error.captureStackTrace(myObject);
    myObject.stack; // Similar to `new Error().stack`

    The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

    The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

    The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

    function a() {
    b();
    }

    function b() {
    c();
    }

    function c() {
    // Create an error without stack trace to avoid calculating the stack trace twice.
    const { stackTraceLimit } = Error;
    Error.stackTraceLimit = 0;
    const error = new Error();
    Error.stackTraceLimit = stackTraceLimit;

    // Capture the stack trace above function b
    Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
    throw error;
    }

    a();

    Parameters

    • targetObject: object
    • OptionalconstructorOpt: Function

    Returns void

  • Parameters

    • err: Error
    • stackTraces: CallSite[]

    Returns any