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
| Property | Type | Default | Description |
|---|---|---|---|
| FetchNativeError | Base Class | — | Base error class with code, message, optional cause, and optional resolved request config. |
| HttpError | Subclass | HTTP_ERROR | Thrown for non-2xx responses. Exposes status, statusText, parsed data, headers, and the Fetch Response. |
| NetworkError | Subclass | NETWORK_ERROR | Thrown on socket drops, airplane mode, or offline conditions where no HTTP response was received. |
| TimeoutError | Subclass | TIMEOUT | Thrown when the configured request timeout expires. Exposes timeoutMs. |
| CancelError | Subclass | CANCELLED | Thrown for caller-initiated cancellation, including cancellation through an AbortSignal. |
| ParseError | Subclass | PARSE_ERROR | Thrown when a successful response body cannot be parsed as the expected response type. |
| ConfigError | Subclass | CONFIG_ERROR | Thrown when invalid request configuration prevents dispatch. |
| RetryExhaustedError | Subclass | RETRY_EXHAUSTED | Thrown when all configured retry attempts have failed. Exposes attempts and lastError. |
| ValidationError | Subclass | VALIDATION_ERROR | Thrown when response payload fails a schema validator (e.g. Zod or StandardSchemaV1). |
| CircuitBreakerError | Subclass | CIRCUIT_OPEN | Thrown 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.