Skip to content

Error Handling

Every error thrown by fetch-smartly is a typed class extending SmartFetchError. Use instanceof to handle each failure case precisely.

Error Hierarchy

Error
 └── SmartFetchError (abstract)
      ├── NetworkError        ERR_NETWORK       (retryable)
      ├── TimeoutError        ERR_TIMEOUT        (retryable)
      ├── HttpError           ERR_HTTP           (retryable per status)
      ├── RateLimitError      ERR_RATE_LIMIT     (retryable)
      └── CircuitOpenError    ERR_CIRCUIT_OPEN   (not retryable)

Usage

typescript
import {
  fetchWithRetry,
  NetworkError,
  TimeoutError,
  HttpError,
  RateLimitError,
  CircuitOpenError,
} from 'fetch-smartly';

try {
  await fetchWithRetry({ url: 'https://api.example.com/data' });
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Rate limited. Retry after:', error.retryAfter, 'ms');
  } else if (error instanceof TimeoutError) {
    console.log('Timed out after', error.timeout, 'ms');
  } else if (error instanceof HttpError) {
    console.log('HTTP', error.status, error.statusText);
    console.log('Response body:', error.body);
  } else if (error instanceof NetworkError) {
    console.log('Network failure:', error.message);
    console.log('Cause:', error.cause);
  } else if (error instanceof CircuitOpenError) {
    console.log('Circuit open until:', new Date(error.resetAt));
  }
}

Common Properties

All SmartFetchError subclasses share these fields:

PropertyTypeDescription
codestringMachine-readable error code
retryablebooleanWhether retry is appropriate
urlstringThe request URL
methodHttpMethodThe HTTP method
timestampnumberWhen the error was created (ms)
messagestringHuman-readable description
causeunknownOriginal error (if applicable)

Error-Specific Properties

Error ClassExtra Properties
NetworkErrorcause — the underlying TypeError
TimeoutErrortimeout — the timeout duration in ms
HttpErrorstatus, statusText, headers, body
RateLimitErrorretryAfter — parsed Retry-After in ms (or null)
CircuitOpenErrorcircuitState, resetAt — when the circuit transitions to half-open

Released under the MIT License.