API Error Handling Lesson

Case Study

API error handling prepares a program for requests that do not work. A server might be down, a URL might be wrong, or the response might return an error status. The page should handle that situation instead of breaking silently.

A try/catch block catches errors from awaited code. Checking response.ok is also important because fetch can receive a response even when the server reports a failure.

Code Runner Challenge

API Error Handling Lesson

View IPYNB Source
%%js

// CODE_RUNNER: API Error Handling Lesson

async function loadScores() {
  try {
    const response = await fetch("/api/scores");

    if (!response.ok) {
      throw new Error("Scores request failed");
    }

    const scores = await response.json();
    console.log(scores);
  } catch (error) {
    console.log("Could not load scores right now.");
  }
}

loadScores();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

The function checks the response before trusting it. If the request fails or the status is not okay, the catch block handles the problem.