Fetch Client API Documentation - v1.1.1
    Preparing search index...

    Class ApiError

    Enhanced API error with detailed context and debugging information

    Extends the native Error class to provide comprehensive error information for API failures. Includes error categorization, retry detection, and debugging context.

    // Handle different error types
    try {
    await api.get('/data');
    } catch (error) {
    if (error instanceof ApiError) {
    console.log('Error code:', error.code); // 'NETWORK_ERROR'
    console.log('HTTP status:', error.status); // 500
    console.log('Can retry:', error.isRetryable); // true
    console.log('Response:', error.response); // Full response object
    }
    }

    Hierarchy

    • Error
      • ApiError
    Index

    Constructors

    • Create a new ApiError instance

      Parameters

      • code: ErrorCode

        Categorized error code for programmatic handling

      • status: number

        HTTP status code (0 for network errors)

      • message: string

        Human-readable error description

      • Optionalresponse: Response | ApiResponse

        Original response object (if available)

      • Optionalrequest: ApiRequest

        Original request object that caused the error

      Returns ApiError

      // Create a custom API error
      throw new ApiError(
      'VALIDATION_ERROR',
      400,
      'Invalid email format',
      response,
      request
      );

    Properties

    timestamp: number

    Timestamp when the error occurred (milliseconds since epoch)

    Useful for error tracking and debugging

    code: ErrorCode

    Categorized error code for programmatic handling

    status: number

    HTTP status code (0 for network errors)

    response?: Response | ApiResponse

    Original response object (if available)

    request?: ApiRequest

    Original request object that caused the error

    Accessors

    • get isRetryable(): boolean

      Check if error is retryable based on error type and status code

      Returns boolean

      True if the error should be retried, false otherwise

      Determines if the error represents a temporary failure that might succeed if retried. Retryable errors include:

      • Network errors (connection issues)
      • Timeout errors (request took too long)
      • Server errors (5xx status codes)
      if (error instanceof ApiError && error.isRetryable) {
      // Attempt retry with exponential backoff
      console.log('Error can be retried');
      } else {
      // Permanent failure, do not retry
      console.log('Error should not be retried');
      }

    Methods

    • Serialize error details to JSON for logging and debugging

      Returns Record<string, unknown>

      Object containing error details suitable for JSON serialization

      Creates a plain object representation of the error that can be safely serialized to JSON for logging, monitoring, or sending to error tracking services.

      try {
      await api.get('/data');
      } catch (error) {
      if (error instanceof ApiError) {
      // Log error details
      console.log(JSON.stringify(error.toJSON(), null, 2));

      // Send to error tracking service
      errorTracker.capture(error.toJSON());
      }
      }
    • Create ApiError from HTTP response

      Parameters

      • response: Response

        The HTTP response that indicates failure

      • Optionalrequest: ApiRequest

        The original request that generated this response

      Returns ApiError

      New ApiError instance with HTTP_ERROR code

      Factory method for creating errors from HTTP responses with 4xx or 5xx status codes. Automatically extracts status code and creates appropriate error message.

      // Handle HTTP error response
      if (!response.ok) {
      const error = ApiError.fromResponse(response, request);
      console.log(error.status); // 404, 500, etc.
      throw error;
      }
    • Create ApiError for timeout scenarios

      Parameters

      • Optionalrequest: ApiRequest

        The request that timed out

      Returns ApiError

      New ApiError instance with TIMEOUT code

      Factory method for creating timeout errors when requests exceed the specified timeout duration. Always uses 408 (Request Timeout) as the HTTP status code.

      // Handle timeout in fetch
      const controller = new AbortController();
      setTimeout(() => controller.abort(), 5000);

      try {
      await fetch(url, { signal: controller.signal });
      } catch (error) {
      if (error.name === 'AbortError') {
      throw ApiError.fromTimeout(request);
      }
      }
    • Create ApiError for network failures

      Parameters

      • error: Error

        The original network error

      • Optionalrequest: ApiRequest

        The request that failed

      Returns ApiError

      New ApiError instance with NETWORK_ERROR code

      Factory method for creating errors from network-level failures like DNS resolution, connection refused, or other connectivity issues. Preserves the original error message for debugging.

      try {
      await fetch(url);
      } catch (error) {
      if (error instanceof TypeError) {
      // Network error (fetch throws TypeError for network issues)
      throw ApiError.fromNetworkError(error, request);
      }
      }
    • Create ApiError for aborted requests

      Parameters

      • Optionalrequest: ApiRequest

        The request that was aborted

      Returns ApiError

      New ApiError instance with ABORTED code

      Factory method for creating errors when requests are manually cancelled using AbortController. Typically occurs when user cancels the request or component unmounts.

      const controller = new AbortController();

      // Cancel request after user action
      cancelButton.onclick = () => controller.abort();

      try {
      await fetch(url, { signal: controller.signal });
      } catch (error) {
      if (error.name === 'AbortError') {
      throw ApiError.fromAbort(request);
      }
      }
    • Create ApiError for response parsing failures

      Parameters

      • dataType: string

        The type of data that failed to parse (e.g., 'json', 'text')

      • status: number

        HTTP status code of the response

      • error: Error

        The original parsing error

      • Optionalresponse: ApiResponse

        The response that failed to parse

      • Optionalrequest: ApiRequest

        The request that generated this response

      Returns ApiError

      New ApiError instance with specific parse error code

      Factory method for creating errors when response data cannot be parsed in the expected format. Automatically generates appropriate error codes like JSON_PARSE_ERROR, TEXT_PARSE_ERROR, etc.

      try {
      const data = await response.json();
      } catch (parseError) {
      throw ApiError.fromParseError(
      'json',
      response.status,
      parseError,
      response,
      request
      );
      }