What is the best practice for handling network errors in data fetching?
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}
Proper network error handling should include: 1) Implementing retry logic with exponential backoff for transient failures, 2) Displaying user-friendly error messages, 3) Providing recovery options when possible, 4) Logging errors for debugging. Additional best practices include:
- Differentiating between different types of errors (network, server, validation)
- Preserving user input during retries
- Implementing offline support where appropriate
- Maintaining consistent error handling across the application