Okay, here's a TypeScript function that fetches user data from an API with error handling (including distinguishing between network errors and API errors) and configurable retry logic with exponential backoff.
First, let's define a type for our user data and for the options:
// Define what user data looks like
interface UserData {
id: number;
name: string;
username: string;
email: string;
// Add other fields as per your API response
}
// Options for our fetch function
interface FetchUserDataOptions {
maxRetries?: number; // Maximum number of retries
initialDelayMs?: number; // Initial delay in milliseconds for retries
retryableStatusCodes?: number[]; // HTTP status codes that should trigger a retry
onRetry?: (attempt: number, error: Error, delayMs: number) => void; // Callback on each retry
}
// Custom error classes for better error handling
class NetworkError extends Error {
constructor(message: string) {
super(message);
this.name = "NetworkError";
}
}
class ApiError extends Error {
public readonly status: number;
public readonly statusText: string;
public readonly body?: any;
constructor(message: string, status: number, statusText: string, body?: any) {
super(message);
this.name = "ApiError";
this.status = status;
this.statusText = statusText;
this.body = body;
}
}
class JsonParseError extends Error {
public readonly originalText: string;
constructor(message: string, originalText: string) {
super(message);
this.name = "JsonParseError";
this.originalText = originalText;
}
}
Now, the main function:
async function fetchUserDataWithRetry(
userId: string | number,
options?: FetchUserDataOptions
): Promise<UserData> {
// Default options
const {
maxRetries = 3,
initialDelayMs = 1000,
// Common transient server errors and rate limiting
retryableStatusCodes = [408, 429, 500, 502, 503, 504],
onRetry,
} = options || {};
let attempts = 0;
let currentDelayMs = initialDelayMs;
const retryableStatuses = new Set(retryableStatusCodes);
const apiUrl = `https://jsonplaceholder.typicode.com/users/${userId}`; // Example API
while (attempts <= maxRetries) {
try {
console.log(`Attempt ${attempts + 1} to fetch user ${userId} from ${apiUrl}...`);
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
// Add any other necessary headers, e.g., Authorization
},
});
if (!response.ok) {
let errorBody;
try {
// Try to parse error response as JSON, common for APIs
errorBody = await response.json();
} catch (e) {
// If not JSON, get as text
errorBody = await response.text().catch(() => 'Could not read error response body');
}
const apiError = new ApiError(
`API request failed with status ${response.status}: ${response.statusText}`,
response.status,
response.statusText,
errorBody
);
// If the status code is retryable and we haven't exhausted retries
if (retryableStatuses.has(response.status) && attempts < maxRetries) {
throw apiError; // Throw to trigger retry logic below
} else {
// Non-retryable API error or max retries reached for a retryable one
console.error(`Non-retryable API error or max retries reached for user ${userId}. Status: ${response.status}`);
throw apiError; // Throw the final error
}
}
// Try to parse the successful response as JSON
const responseText = await response.text();
try {
const data: UserData = JSON.parse(responseText);
console.log(`Successfully fetched data for user ${userId}.`);
return data;
} catch (e) {
throw new JsonParseError(
`Failed to parse JSON response for user ${userId}. Error: ${(e as Error).message}`,
responseText
);
}
} catch (error: any) { // Catching 'any' to handle different error types
attempts++;
// If it's a non-retryable ApiError (because it wasn't in retryableStatusCodes or attempts hit maxRetries earlier)
// or if it's a JsonParseError, or if we've exhausted retries for any error.
if (
(error instanceof ApiError && !retryableStatuses.has(error.status)) ||
error instanceof JsonParseError ||
attempts > maxRetries
) {
console.error(
`Failed to fetch user ${userId} after ${attempts} attempt(s). Final error:`,
error.name, error.message, (error as ApiError).body || (error as JsonParseError).originalText || ''
);
throw error; // Re-throw the caught error (could be ApiError, JsonParseError, or NetworkError from fetch)
}
// At this point, it's a retryable error (NetworkError or retryable ApiError)
// and we still have attempts left.
// If fetch itself failed (e.g., network issue, DNS, CORS if not configured server-side)
// it throws a TypeError in browsers, which we'll wrap as NetworkError.
// Or if it was a retryable ApiError thrown from the 'if (!response.ok)' block.
const currentError = (error instanceof ApiError) ? error : new NetworkError(error.message || 'Unknown network error');
console.warn(
`Attempt ${attempts} for user ${userId} failed: ${currentError.name} - ${currentError.message}. ` +
`Retrying in ${currentDelayMs / 1000}s...`
);
if (onRetry) {
onRetry(attempts, currentError, currentDelayMs);
}
await new Promise(resolve => setTimeout(resolve, currentDelayMs));
currentDelayMs *= 2; // Exponential backoff
}
}
// This line should theoretically be unreachable if maxRetries >= 0,
// as the loop will either return data or throw an error.
// Added for completeness and to satisfy TypeScript's control flow analysis.
throw new Error(`Exhausted all ${maxRetries + 1} retries for user ${userId} without success.`);
}
// --- Example Usage ---
async function main() {
// 1. Successful fetch
try {
const user1 = await fetchUserDataWithRetry(1);
console.log("Fetched User 1:", user1.name);
} catch (error: any) {
console.error("Error fetching user 1:", error.message);
if (error instanceof ApiError) {
console.error("API Error Details:", { status: error.status, body: error.body });
}
}
console.log("\n-------------------\n");
// 2. User not found (404 - typically non-retryable by default)
try {
const userNonExistent = await fetchUserDataWithRetry(999); // This user likely doesn't exist
console.log("Fetched Non-Existent User:", userNonExistent);
} catch (error: any) {
console.error("Error fetching non-existent user:", error.message);
if (error instanceof ApiError) {
console.error("API Error Details:", { status: error.status, body: error.body });
}
}
console.log("\n-------------------\n");
// 3. Simulating a temporarily failing API (e.g., to test retry logic)
// (You'd need to mock 'fetch' or use a test server to truly test retries for 500 errors)
// For this example, let's try a user ID that might cause an issue or override options.
try {
console.log("Attempting fetch with retry for a potentially problematic ID or custom options:");
const userProblematic = await fetchUserDataWithRetry("abc", { // Invalid ID, jsonplaceholder will 404
maxRetries: 2,
initialDelayMs: 500,
retryableStatusCodes: [404, 500], // Let's make 404 retryable for this test
onRetry: (attempt, err, delay) => {
console.log(`Custom onRetry: Attempt ${attempt}, Error: ${err.message}, Next delay: ${delay}ms`);
},
});
console.log("Fetched Problematic User:", userProblematic);
} catch (error: any) {
console.error("Error fetching problematic user:", error.message);
if (error instanceof ApiError) {
console.error("API Error Details:", { status: error.status, body: error.body });
} else if (error instanceof JsonParseError) {
console.error("JSON Parse Error. Original Text:", error.originalText);
}
}
console.log("\n-------------------\n");
// 4. Test network error (e.g. by providing an invalid URL - fetch will reject)
// For this, we'd have to modify the apiUrl inside fetchUserDataWithRetry or mock fetch.
// Let's modify the function slightly for a quick test of this (not ideal for production):
// You could pass the full URL instead of just userId to make this easier.
// Or, more robustly, use a library like `nock` for testing network errors.
// For a simple demonstration, imagine 'fetch' itself fails.
// The current structure will catch this and treat it as a retryable network error.
// To test this without mocking, you could temporarily change `apiUrl` to something like `https://nonexistentdomain.foobar`
// inside the function and run that specific test.
}
main();
Key Features and Explanations:
UserData Interface: Defines the expected structure of the user data.
FetchUserDataOptions Interface:
maxRetries: How many times to retry after the initial failed attempt.
initialDelayMs: The starting delay before the first retry.
retryableStatusCodes: An array of HTTP status codes that are considered transient and should trigger a retry (e.g., 500, 503, 429 for rate limiting).
onRetry: A callback function that is executed before each retry attempt. Useful for logging or custom logic.
- Custom Error Classes (
NetworkError, ApiError, JsonParseError):
- This allows you to distinguish between different types of errors in your calling code using
instanceof.
ApiError includes the status code and potentially the error body from the API.
JsonParseError includes the raw text that failed to parse.
- Retry Loop (
while (attempts <= maxRetries)):
- The loop continues as long as the number of
attempts is less than or equal to maxRetries.
fetch() API: Used for making the HTTP request.
- Response Handling:
!response.ok: Checks if the HTTP status code indicates an error (e.g., 4xx or 5xx).
- If
!response.ok:
- It attempts to parse the error response body (first as JSON, then as text).
- It creates an
ApiError.
- It checks if the
response.status is in the retryableStatusCodes set.
- If retryable and retries are left, it
throws the ApiError to be caught by the outer catch block for retry logic.
- If not retryable or retries are exhausted, it
throws the ApiError to be propagated to the caller.
- If
response.ok:
- It attempts to parse the response body as JSON.
- If parsing fails, it throws a
JsonParseError.
- If successful, it returns the .
This function provides a robust way to interact with APIs, gracefully handling common issues and improving the resilience of your application.