🟒 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