Conditional Retries Based on Error Type
What you'll learn: How to implement smart retry logic that adapts based on whether you're facing network failures, timeouts, or server errors.
Not all errors deserve the same treatment. Imagine a doctor treating every symptom with the same medicine—ineffective and potentially harmful. Your retry logic should be equally discerning.
Why Error Types Matter
When a request fails, the reason determines if retrying makes sense:
- Network errors (connection lost, DNS failure): Often transient. Retry aggressively with exponential backoff.
- Timeouts: The server might be slow or overloaded. Retry with longer delays or fewer attempts.
- 5xx Server errors (500, 502, 503): Server-side issues. Retry cautiously—the server might need time to recover.
- 4xx Client errors (400, 404, 401): Your request is wrong. Don't retry—you'll get the same error.
Implementation Strategy
When catching errors, inspect the response status or error type:
async function fetchWithSmartRetry(url, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url);
if (!response.ok) {
// Server returned error status
if (response.status >= 500) {
// Retry server errors
await backoff(attempt);
continue;
} else if (response.status >= 400) {
// Don't retry client errors
throw new Error(`Client error: ${response.status}`);
}
}
return response;
} catch (error) {
// Network error or timeout
if (error.name === 'AbortError') {
// Timeout - retry with caution
if (attempt < 1) await backoff(attempt);
else throw error;
} else {
// Network error - retry normally
await backoff(attempt);
}
}
}
}
Different error types get different treatment: aggressive retries for network issues, cautious retries for server errors, and no retries for client mistakes.
Key Takeaway: Match your retry strategy to the error type—retry transient network and server errors, but never retry client errors that won't change on subsequent attempts.