Exercise 18: Fetch and Handle Different Status Codes

Problem Statement

Function `fetchWithStatusHandling(url)` banao jo different status codes ko handle kare. Example: fetchWithStatusHandling(url) → 200: data, 404: null, 500: error

Sample Output:

await fetchWithStatusHandling(url)
// 200: returns JSON, 404: returns null, 500+: throws error

Solution

const fetchWithStatusHandling = async (url) => {
  const res = await fetch(url);
  if (res.status === 200) return res.json();
  if (res.status === 404) return null;
  if (res.status >= 500) throw new Error(`Server error: ${res.status}`);
  throw new Error(`HTTP ${res.status}`);
};

Explanation

Overall Goal:

  • Different status codes ko handle karna.

Real world:

  • Error handling: status-based handling.
  • API responses: status code handling.