Responses & Errors

Check response.ok

fetch only rejects on network failures. A 404 or 500 response still resolves, so always check response.ok (status 200–299):

async function getJson(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

try {
  const post = await getJson("https://jsonplaceholder.typicode.com/posts/99999");
} catch (err) {
  console.log("Request failed:", err.message);   // "HTTP 404"
}

Loading, Error and Empty States

Example

A real UI shows what is happening:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<button id="go">Load posts</button>
<ul id="list"></ul>
<p id="status"></p>
<script>
  const status = document.getElementById("status");
  const list = document.getElementById("list");
  document.getElementById("go").addEventListener("click", async () => {
    status.textContent = "Loading...";
    list.innerHTML = "";
    try {
      const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
      if (!res.ok) throw new Error("HTTP " + res.status);
      const posts = await res.json();
      for (const p of posts) {
        const li = document.createElement("li");
        li.textContent = p.title;
        list.append(li);
      }
      status.textContent = posts.length ? "" : "No posts found.";
    } catch (err) {
      status.textContent = "Could not load posts: " + err.message;
    }
  });
</script>

</body>
</html>

Result