Here's a TypeScript function that fetches user data from an API, with built-in error handling and retry logic. The function retries the request a specified number of times if it fails due to network issues or server errors (e.g., 5xx), with a delay between each retry.
✅ Features:
Uses fetch API.
Retries on failure up to a configurable number of times.
Adds exponential backoff delay between retries.
Handles common HTTP error codes.
Returns typed user data (User interface).
🧩 Example Code
typescript
// Define a User type
interface User {
id: number;
name: string;
email: string;
}
// Fetch user data with retry logic
async function fetchUserData(userId: number, maxRetries: number = 3): Promise<User> {
const url = `https://api.example.com/users/${userId}`;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url);
// Handle non-2xx responses
if (!response.ok) {
const errorMessage = `HTTP error! Status: ${response.status}`;
// Retry only for 5xx errors
if (response.status >= 500 && response.status < 600) {
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff: 2s, 4s, 8s...
console.warn(`Attempt ${attempt} failed with server error. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
} else {
throw new Error(`${errorMessage} (gave up after ${maxRetries} attempts)`);
}
} else {
throw new Error(errorMessage);
}
}
const data: User = await response.json();
return data;
} catch (error) {
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000;
console.warn(`Network error on attempt ${attempt}:`, error, `. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw new Error(`Failed to fetch user data after ${maxRetries} attempts: ${error}`);
}
}
}
throw new Error('Unexpected error during fetch'); // Should not reach here
}