Error Handling & Type Guards

All errors thrown by the client belong to an object-oriented, strongly-typed error hierarchy with dedicated TypeScript type guards.


Handling Errors with Type Guards

Instead of fragile err.code === 'ECONNABORTED' string checking, use the exported boolean type guards to safely inspect and narrow errors:

errors.ts
typescript
import {
  createClient,
  isHttpError,
  isTimeoutError,
  isNetworkError,
  isCancelError,
} from 'react-native-fetch-client';

const api = createClient({ baseURL: 'https://api.example.com' });

try {
  const res = await api.get('/protected-resource');
  console.log(res.data);
} catch (err) {
  if (isHttpError(err)) {
    // 4xx or 5xx HTTP response
    console.error(`HTTP ${err.status}: ${err.statusText}`);
    console.error('Response data:', err.data);
  } else if (isTimeoutError(err)) {
    // Request timed out
    console.error(`Request timed out after ${err.timeoutMs}ms`);
  } else if (isNetworkError(err)) {
    // Device is offline or DNS failed
    console.error('Network connectivity failure:', err.message);
  } else if (isCancelError(err)) {
    // Aborted via AbortController or cancelPrevious
    console.log('Request was deliberately cancelled');
  } else {
    console.error('Unexpected error:', err);
  }
}

Error Class Hierarchy

Exported Error Classes
PropertyTypeDefaultDescription
FetchNativeErrorBase Class—Base error class with code, message, optional cause, and optional resolved request config.
HttpErrorSubclassHTTP_ERRORThrown for non-2xx responses. Exposes status, statusText, parsed data, headers, and the Fetch Response.
NetworkErrorSubclassNETWORK_ERRORThrown on socket drops, airplane mode, or offline conditions where no HTTP response was received.
TimeoutErrorSubclassTIMEOUTThrown when the configured request timeout expires. Exposes timeoutMs.
CancelErrorSubclassCANCELLEDThrown for caller-initiated cancellation, including cancellation through an AbortSignal.
ParseErrorSubclassPARSE_ERRORThrown when a successful response body cannot be parsed as the expected response type.
ConfigErrorSubclassCONFIG_ERRORThrown when invalid request configuration prevents dispatch.
RetryExhaustedErrorSubclassRETRY_EXHAUSTEDThrown when all configured retry attempts have failed. Exposes attempts and lastError.
ValidationErrorSubclassVALIDATION_ERRORThrown when response payload fails a schema validator (e.g. Zod or StandardSchemaV1).
CircuitBreakerErrorSubclassCIRCUIT_OPENThrown immediately when requests are blocked because the circuit breaker is OPEN.
Prefer No Try/Catch?
If you want to avoid try/catch boilerplate entirely, check out the Safe Requests API (api.safe.*) which returns Go/Rust style [data, error] tuples.