Start learning free

LESSON 52 OF 161 · FRONTEND: TALKING TO AN API

When the Server Fails

Practice

Sometimes the network works but the server itself has a problem. It still answers, with a status like 500, a server error. To fetch that is an answer like any other: it does not throw, so catch never hears about it. Only response.ok tells you. It is false for every status outside 200 to 299.

So check ok before you read the answer, and stop when it is false. A page that loads the categories, for example, could do this:

const response = await fetch("/api/categories");
if (!response.ok) {
  note.textContent = "Categories are not available";
  return;
}

Show the visitor plain words, never the server's raw answer: that is written for developers. A server failure and a network failure end the same way, with words in the message line and the Try again button. So write those two lines once, in a function showError(text), and call it from both places with their own words.

The check makes the API answer 500, then goes offline and clicks Try again, then goes online and clicks it again. Your page must show:

> the API will answer GET /api/products with 500
> open the page
  request: GET /api/products -> 500
    text: The shop has a problem, try again later
    button: Try again
    text: 0 products
> the network goes offline
> click "Try again"
  request: GET /api/products -> failed: the network is offline
    text: Can't reach the shop
> the network goes online
> click "Try again"
  request: GET /api/products -> 200
    text: 8 products   (the message and Try again are gone)

Your task: in app.js, write showError(text), which shows the words and the Try again button. Call it from catch with "Can't reach the shop". After the fetch, when response.ok is false, call it with "The shop has a problem, try again later" and return.


Assignment
Follow the Coding Tutorial to write showError, use it in catch, and check response.ok right after the fetch in loadProducts.


Hint
!response.ok is true when the answer is not OK. Don't forget the return: without it, the code goes on and tries to draw the error answer as if it were the product list.


STEP 1 OF 7
    Ctrl + Enter to check