Theory

The four outcomes of a fetch

In lessons 4–5 the gallery worked — when all went well. But the network fails in reality, and every request has not one but four outcomes:

  • Loading — sent, waiting.
  • Loaded — we have data, show it.
  • Empty — got a response, but there's nothing in it (or the search matched nothing).
  • Error — the network or the API failed.

"Empty" and "error" are the ones people forget — and they're exactly what separates "looks broken" from "all good".

Typed errors. The problem with throw new Error('something broke') is that the caller can't tell what happened: a network failure, a rate limit (429), or a 404. And the response differs: for a rate limit — "wait / get your own key"; for the network — "try again". So we make error classes: NetworkError, RateLimitError, NotFoundError, ApiError — each with a retryable flag, so the UI knows whether to offer "Retry".

And the key data case — media_type. APOD returns, each day, either an image or a video (media_type: 'image' | 'video'). Some days are videos (often YouTube). If you blindly put pic.url into an <img>, a video link, you get a broken image. You have to check media_type and branch.

(A forward flag: in lesson 16, TypeScript makes this media_type check mandatory — forgetting it simply won't be possible. But for now — we check it ourselves.)