Leet School

{module 6}

When a request fails

How programs talk to each other20 min read

What you will be able to do

  • Give a page that loads data three states, loading, empty and error, and make each one appear on purpose.
  • Catch a request that fails with try and catch, and tell it apart from a request the server refuses.
  • Add a button that tries the request again without reloading the page.

Why it matters

Yucatán Hammocks makes cotton hammocks by hand in Mérida, Mexico. The cotton is dyed and dried in the yard, and one shower can spoil a day's work. Luis Canul, who runs the workshop, asked for a page on the workshop's tablet that lists the days in the coming week when rain is likely.

The first version worked in the office. In the yard, where the wireless signal is weak, it showed "Loading the forecast" all day. Nobody could tell whether the forecast was slow, broken, or simply showing no rain. One morning the team dried cotton outside, trusting a page that had never loaded, and lost a batch in the afternoon rain.

A page that loads data must say something true at every moment. This lesson shows you how.

The idea

Three states

While a page waits for data, and after the answer arrives, it is always in one of three states. Each needs its own message.

  • Loading. The request is on its way. Say so, so the visitor knows to wait.
  • Empty. The answer arrived and holds nothing to show. "No rain is likely in the next seven days" is a fact. An empty list looks like a fault.
  • Error. No usable answer came. Say what the visitor can do, and give them a way to try again.

Write these three messages before you write the request. They are part of the page, as much as the data.

Two ways a request goes wrong

In lesson 3 the server answered 500. That is a refused request: an answer arrived, and response.ok was false. Your if handles it.

A failed request is different. No answer arrives at all: the visitor is offline, the signal dropped, or the server could not be reached. There is no status code to check. The promise that fetch returned is rejected, and await turns that into an error: JavaScript stops the function at that line and reports the problem. Without anything to catch it, the error ends up in the Console, and the page stays as it was, on "Loading", for ever.

The two cases need different messages. When the server refuses, the visitor's connection is fine, and waiting a few minutes may help. When the request fails, the first thing to check is the connection.

try and catch

try and catch let your code handle an error instead of stopping:

From rain.js
  try {
    const response = await fetch(address);

JavaScript runs the lines inside try { } one by one. If any of them throws an error, it jumps straight to catch, skipping the rest:

From rain.js
  } catch (error) {
    console.log(`The request failed: ${error.message}`);
    showError("The forecast did not load. Check your connection, then try again.");
  }

error is an object that describes what went wrong, and error.message is its text. Log it for yourself in the Console. Show the visitor a sentence they can act on.

A button to try again

A visitor in the yard should not have to know about reloading. A button does it for them. It starts with the hidden attribute, which hides any element:

From index.html
      <button type="button" id="retry" hidden>Try again</button>

In JavaScript, retryButton.hidden = false shows it, and true hides it again. The button runs the same function that loaded the page in the first place:

From rain.js
retryButton.addEventListener("click", loadForecast);

Worked example

This is Luis's page, rebuilt with all three states. The answer from Open-Meteo holds two lists in the same order: the dates in daily.time, and the highest chance of rain on each day, in percent, in daily.precipitation_probability_max. You met that shape in lesson 2.

Create index.html:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Rain this week, Yucatán Hammocks</title>
    <script src="rain.js" defer></script>
  </head>
  <body>
    <main>
      <h1>Rain this week in Mérida</h1>
      <p id="status">Loading the forecast for Mérida</p>
      <button type="button" id="retry" hidden>Try again</button>
      <ul id="rain-days"></ul>
      <p><a href="https://open-meteo.com/">Weather data by Open-Meteo.com</a></p>
    </main>
  </body>
</html>

Then rain.js:

rain.js
const address =
  "https://api.open-meteo.com/v1/forecast?latitude=20.97&longitude=-89.62&daily=precipitation_probability_max&timezone=auto";

const statusLine = document.querySelector("#status");
const retryButton = document.querySelector("#retry");
const list = document.querySelector("#rain-days");

function showError(message) {
  statusLine.textContent = message;
  retryButton.hidden = false;
}

// The dates and the chances are two lists in the same order, so one counter reads both.
function showRainDays(daily) {
  let position = 0;
  let rainDays = 0;
  for (const date of daily.time) {
    const chance = daily.precipitation_probability_max[position];
    if (chance >= 50) {
      const item = document.createElement("li");
      item.textContent = `${date}: ${chance}% chance of rain`;
      list.append(item);
      rainDays = rainDays + 1;
    }
    position = position + 1;
  }
  return rainDays;
}

async function loadForecast() {
  console.log("Asking for the forecast");
  statusLine.textContent = "Loading the forecast for Mérida";
  retryButton.hidden = true;
  list.textContent = "";
  try {
    const response = await fetch(address);
    if (!response.ok) {
      showError(`The weather service answered ${response.status}. Try again in a few minutes.`);
      return;
    }
    const forecast = await response.json();
    const rainDays = showRainDays(forecast.daily);
    if (rainDays === 0) {
      statusLine.textContent = "No rain is likely in the next seven days.";
    } else {
      statusLine.textContent = `Rain is likely on ${rainDays} of the next seven days:`;
    }
  } catch (error) {
    console.log(`The request failed: ${error.message}`);
    showError("The forecast did not load. Check your connection, then try again.");
  }
}

retryButton.addEventListener("click", loadForecast);
loadForecast();

Each state below is what the page really showed.

Loading. Before the answer arrives, the page shows the text in the HTML:

Output
Rain this week in Mérida

Loading the forecast for Mérida

Weather data by Open-Meteo.com

With data. With the real answer from Open-Meteo saved when this lesson was written:

Output
Rain this week in Mérida

Rain is likely on 2 of the next seven days:

2026-11-17: 57% chance of rain
2026-11-18: 76% chance of rain

Weather data by Open-Meteo.com

Empty. With an answer in which no day reaches 50%:

Output
Rain this week in Mérida

No rain is likely in the next seven days.

Weather data by Open-Meteo.com

Refused. The server answered 500:

Output
Rain this week in Mérida

The weather service answered 500. Try again in a few minutes.

Try again

Weather data by Open-Meteo.com
page error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Failed. There was no connection. The last three lines are from the Console:

Output
Rain this week in Mérida

The forecast did not load. Check your connection, then try again.

Try again

Weather data by Open-Meteo.com
Asking for the forecast
The request failed: Failed to fetch
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED

"Failed to fetch" is the message of the error that fetch threw. The browser adds its own line about the failed request.

Lines 15 to 26 read both lists with one counter. position starts at 0, and each turn of the loop adds 1, so the chance on line 18 always belongs to the date on line 17. Lines 32 to 34 put the page back into its loading state at the start of every attempt, including a retry. Setting textContent to "" empties the list, so an old answer is never shown twice. === on line 43 means "is equal to".

Common mistakes

No try and catch

In no-try.js, the same lines run without try and catch. With no connection:

Output
Rain this week in Mérida

Loading the forecast for Mérida

Weather data by Open-Meteo.com
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED
page error: Uncaught (in promise) TypeError: Failed to fetch

This is Luis's first version. "Uncaught" means no catch handled the error, so the function stopped and the page kept saying "Loading". Only someone with the Console open would ever know.

No empty state

In no-empty.js, the status line changes only when there is rain:

From no-empty.js
    if (rainDays > 0) {
      statusLine.textContent = `Rain is likely on ${rainDays} of the next seven days:`;
    }

With a dry week, there is no error at all:

Output
Rain this week in Mérida

Loading the forecast for Mérida

Weather data by Open-Meteo.com

The answer arrived, and the page still claims to be loading. Every path through the function must end with a message that is true.

Calling the function instead of naming it

In call-at-once.js, the last lines have brackets after the function name: retryButton.addEventListener("click", loadForecast());. With no connection, the Console shows this before anyone clicks:

Output
Asking for the forecast
Asking for the forecast
The request failed: Failed to fetch
The request failed: Failed to fetch
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED

Two requests went out at once, and clicking the button afterwards sends none. loadForecast() with brackets runs the function immediately and hands its result to addEventListener. Without brackets, loadForecast is the name of the function, to run later, on each click.

Think it through

Nadia, a learner, wants to check that her retry button really sends a new request, and does not only change the text.

Understand. After a failure, one click must send exactly one new request, and the page must show the right state afterwards.

Break down. Make the request fail. Click the button. Count the requests. Read the page.

Plan. Line 31 logs "Asking for the forecast" at every attempt. She will make the request fail, click once, and count those lines in the Console.

Build. She opens the page with the Network panel set to Offline, as in Task 2 below, waits for "Try again", and clicks it once.

Test. The Console shows:

Output
Asking for the forecast
The request failed: Failed to fetch
Asking for the forecast
The request failed: Failed to fetch
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED
page error: Failed to load resource: net::ERR_INTERNET_DISCONNECTED

Two attempts, one from loading and one from her click. Then she sets the Network panel back to no throttling, clicks again, and the list of rain days appears with no reload.

Reflect. One log line at the start of the function made the test possible. She will keep a line like it in every function that sends a request.

At work

When you present your work, say what does not work yet. The client will find out anyway, and it is better that they hear it from you, with a plan.

Valentina, who built Luis's page, ended her handover with this:

What does not work yet: the page asks for the forecast once, when it opens. If the tablet stays on all day, the forecast on screen is from the morning. For now, press Try again or reload after lunch. A version that asks again every hour is about half a day of work, if you want it.

She named the limit, what it means for the team, what to do today, and what it would take to remove it. She did not apologise, and she did not hide it at the end of a long message.

Your tasks

Task 1: Build the page

Build the worked example and open it with the Console open.

You are done when the page shows either a list of rain days or the sentence for a dry week, and the Console shows "Asking for the forecast" once.

Task 2: Make every state appear

Open the developer tools and the Network panel. Its toolbar has a throttling menu, which says "No throttling" at first. In Chrome and Edge, choose Offline. In Firefox, the same menu is called Throttling, and it also has Offline. Reload the page and read the error. Set the menu back, and click Try again. For the loading state, choose the slowest speed in the same menu, such as 3G, and reload. Set it back afterwards.

You are done when you have seen the loading message, the error with the button, and the list or the empty sentence after the button, all on your own screen.

Task 3: Make the server refuse

Change forecast in the address to forcast, save, and reload. You saw this mistake in lesson 1.

You are done when the page shows the refused message with the status code 404, and the button. Put the address back.

Task 4: Hide the list during loading

While the page loads, the empty ul is still on the page, and a screen reader may announce it as a list with no items. Change the code so that the list itself is hidden while loading and after an error, and shown only when it has days in it.

You are done when the list is hidden in the loading, error and empty states, and visible with two days in it when rain is likely, including after a successful retry.

Recap

  • A page that loads data has three states: loading, empty and error. Write their messages first.
  • A refused request has a status code, and response.ok is false. A failed request has no answer at all, and fetch throws an error.
  • Put the request inside try, and handle the failure in catch with a message the visitor can act on.
  • A retry button runs the same function again. Pass the function's name to addEventListener, without brackets.

Go deeper