async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
const data = await res.json();
console.log('Got user:', data);
return data;
} catch (err) {
console.error('Network error:', err);
return null;
}
}async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
const data = await res.json();
console.log('Got user:', data);
return data;
} catch (err) {
console.error('Request failed:', err);
return null;
}
}Bug: fetch() only rejects on network failure. HTTP 404/500 responses are "successful" β res.json() returns the error body and the catch never runs.
Explanation: Always check res.ok after fetch. It's false for 4xx and 5xx responses. Throw a meaningful error so the catch block handles all failures β network AND HTTP errors.
Key Insight: fetch() resolves for ANY HTTP response. Only network failures (no connection, DNS fail) cause rejection. Always check res.ok.