Error Handling
Error Handling
Section titled “Error Handling”Introduction
Section titled “Introduction”Fetch only rejects on network errors, not HTTP errors. You must check response.ok for HTTP error status codes.
The Key Difference
Section titled “The Key Difference”// ❌ This only catches NETWORK errorstry { const response = await fetch('/api/not-found'); // 404 // No error thrown for 404!} catch (error) { // Only catches network failures}
// ✅ You must check response.okconst response = await fetch('/api/not-found');if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`);}Complete Error Handler
Section titled “Complete Error Handler”async function fetchWithErrorHandling(url) { try { const response = await fetch(url);
if (!response.ok) { const errorData = await response.json().catch(() => null); throw new Error( errorData?.message || `HTTP ${response.status}: ${response.statusText}` ); }
return await response.json(); } catch (error) { if (error.name === 'TypeError') { console.error('Network error (no internet, CORS, etc.):', error); } else { console.error('Request failed:', error); } throw error; }}Summary
Section titled “Summary”- Fetch only rejects on network errors
- Check
response.okfor HTTP errors (4xx, 5xx) - Network errors throw
TypeError - Always handle both error types