🟑 MediumAsync BugsπŸ› Debug Challenge

Not handling fetch HTTP errors

Buggy Code β€” Can you spot the issue?

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;
  }
}

Fixed Code

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 Explained

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.

More Async Bugs Debug Challenges

🟒 EasyMissing await causes wrong resultβ†’πŸŸ‘ MediumSequential awaits killing performanceβ†’πŸŸ‘ MediumSwallowed error in async functionβ†’πŸ”΄ HardAsync function in forEachβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab