EasyBrowser APIs📖 Theory Question

What is the Fetch API and how do you handle errors correctly?

💡

Hint

fetch() only rejects on network failure — HTTP 4xx/5xx must be checked via response.ok

Full Answer

The key gotcha: fetch() only rejects on network failure (no connection, DNS fail). HTTP errors like 404 or 500 are "successful" responses!

// ❌ Wrong — HTTP errors silently "succeed"
const data = await fetch('/api').then(r => r.json());
// 404 or 500 still "resolves" — you get error HTML as data

// ✅ Correct — check response.ok
async function apiFetch(url, options = {}) {
  const res = await fetch(url, options);
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}: ${res.statusText}`);
  }
  return res.json();
}

// POST with JSON
await apiFetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' }),
});

// With timeout (AbortController)
async function fetchWithTimeout(url, ms = 5000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), ms);
  try {
    return await fetch(url, { signal: controller.signal });
  } catch (err) {
    if (err.name === 'AbortError') throw new Error('Request timed out');
    throw err;
  } finally {
    clearTimeout(id);
  }
}
💡 Always check response.ok. Create a reusable fetch wrapper that throws on non-2xx responses so every call site doesn't have to remember.

More Browser APIs Questions

EasyWhat is the difference between localStorage, sessionStorage, and cookies?→MediumWhat are Web Workers and when should you use them?→MediumWhat are Service Workers and what problems do they solve?→MediumWhat is the Same-Origin Policy and how does CORS work?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint