Start learning free

LESSON 39 OF 58 · FULL-STACK: WHEN THINGS GO WRONG

The API Is Down

Practice

Until now every error came with an answer from the server: a 401, a 409, a 500. Sometimes no answer comes at all: the visitor's Wi-Fi drops, or the API isn't running. Then fetch doesn't return a response. It throws a TypeError, and the page's api() fails with it.

The fix is a try/catch around the fetch that turns the failure into an ApiError the pages understand. Status 0 means "no answer came back" (no real HTTP answer has status 0), and the message tells the truth: Can't reach the shop. There's one trap. A variable declared with const inside try { } doesn't exist below the block. Declare it above with let and assign it inside, like this, with another value:

let settings;
try {
  settings = JSON.parse(saved);
} catch (err) {
  settings = {};
}

The pages are given: for status 0 they show a banner with Try again and keep the cart on the screen. With a Mug and a Lamp in Ana's cart, the check does this:

network offline, click "+" on Mug  →  PUT /api/cart/1  failed: the network is offline
  page: alert "Can't reach the shop", button "Try again", the cart still listed
click "Try again" (still offline)  →  GET /api/cart  failed, the banner stays
network online, click "Try again"  →  GET /api/cart  →  200, the banner goes away
click "+" on Mug                   →  PUT /api/cart/1 {"quantity": 2}  →  200
  page: Mug × 2 $24, Total: $53

Your task: in client/src/api.js, the empty try and catch are given. Declare response above them and fill it with the fetch answer inside try. Inside catch, throw a new ApiError with status 0 and the message "Can't reach the shop".


Assignment
Follow the Coding Tutorial to make api() turn a failed fetch into an ApiError with status 0.


Hint
Inside try, write response = await fetch(...) without const, because the variable already exists. Only the fetch goes inside try. response.json() stays below the block, so real error answers work as before.


STEP 1 OF 3
    Ctrl + Enter to check