LOGBOOK

HELP

Quiz Entry - updated: 2026.06.23

When fetching a stationboard, why wrap the call in try…catch and check response.ok separately?

Because fetch only rejects on network failure, not on HTTP error statuses — so you need both: try…catch for the network, and an explicit response.ok check for 4xx/5xx responses.

try {
  const url = 'https://transport.opendata.ch/v1/stationboard?id='
    + station + '&limit=15';

  const response = await fetch(url, {
    method: 'GET',
    signal: AbortSignal.timeout(5000)
  });

  if (response.ok) {                        // HTTP 200–299?
    const result = JSON.parse(await response.text());
    displayStationboard(result);            // hand JSON to the renderer
  } else {
    throw Error('fetch failed with status: ' + response.status);
  }
} catch (error) {                           // network error or thrown Error
  alert('fetch failed: ' + error);
}

This is a famous fetch gotcha: a 404 or 500 is a successful network round-trip, so fetch resolves normally — response.ok is false but no exception is thrown. If you only relied on catch, you'd treat an error page as valid data. The catch block then handles the other failure class: the connection dropping or the 5-second timeout firing.

Tip: response.ok is true for status 200–299. Anything else (301, 404, 500) needs explicit handling — checking .ok is the idiomatic way.

From Quiz: WEBT / External Webservices | Updated: Jun 23, 2026