0Pricing
JavaScript Academy · Lesson

Handling Errors and Status Codes

Check response.ok and handle failures.

Handling Errors and Status Codes is a free JavaScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Fetch Does Not Reject on HTTP Errors

A surprising gotcha: fetch only rejects on network failures. A 404 or 500 response still resolves successfully. You must check the status yourself.

Checking response.ok

response.ok is true only for status codes in the 200-299 range. Use it to detect HTTP errors.

const response = await fetch(url);
if (!response.ok) {
  console.log("HTTP error:", response.status);
}

Reading the Status Code

response.status gives the numeric code and response.statusText a short message. Branch on these to handle specific cases.

if (response.status === 404) console.log("Not found");
if (response.status === 401) console.log("Unauthorized");

Throwing on Bad Status

A clean pattern is to throw an Error when the response is not ok, so a single catch handles both network and HTTP failures.

if (!response.ok) {
  throw new Error("Request failed: " + response.status);
}

Wrapping in try/catch

With async/await, wrap the whole flow in try/catch. Network errors reject the Promise and land in catch; your thrown HTTP error does too.

try {
  const res = await fetch(url);
  if (!res.ok) throw new Error("Status " + res.status);
  const data = await res.json();
} catch (err) {
  console.log("Failed:", err.message);
}

Distinguishing Error Types

A rejected fetch usually means the server was unreachable, DNS failed, or CORS blocked it. A non-ok response means the server answered but with an error. Handle them differently when it matters.

Reading Error Bodies

APIs often return JSON describing the error. Read it before throwing so you can surface a useful message.

if (!res.ok) {
  const errBody = await res.json().catch(() => ({}));
  throw new Error(errBody.message || ("Status " + res.status));
}

Common Status Codes

Know the families: 2xx success, 3xx redirect, 4xx client error (you sent something wrong), 5xx server error (their fault). Fetch auto-follows most redirects.

A Reusable Helper

Centralize the check in one helper so every call site gets consistent error handling.

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

Retrying Transient Failures

For flaky networks you may retry on 5xx or network errors. Keep retries small and add a delay to avoid hammering the server.

for (let i = 0; i < 3; i++) {
  try { return await getJSON(url); }
  catch (e) { if (i === 2) throw e; }
}

Surfacing to the User

Catch errors at the UI layer to show a friendly message instead of a blank screen. Never let an unhandled rejection silently swallow a failed request.

getJSON(url)
  .then(render)
  .catch(() => showToast("Could not load data"));

Quick Check

Fetch error handling.

Recap

Fetch rejects only on network failures, so always check response.ok/response.status and throw on bad statuses. Wrap calls in try/catch, read error bodies for messages, centralize the check in a helper, and surface friendly errors in the UI.

Frequently asked questions

Is the “Handling Errors and Status Codes” lesson free?

Yes — the full text of “Handling Errors and Status Codes” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Handling Errors and Status Codes”?

Check response.ok and handle failures. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Handling Errors and Status Codes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Making GET Requests
  2. POST and Sending Data
  3. Handling Errors and Status Codes
  4. Aborting Requests with AbortController
← Back to JavaScript Academy