neuefische / web-exercises

Session exercises
MIT License
17 stars 33 forks source link

Fix promise try/catch scenario #338

Closed moonwave99 closed 9 months ago

moonwave99 commented 9 months ago

The spirit of this exercise is that one can have multiple source of errors - in this case both a 404 and a non-JSON existing page.

Since !response.ok per se does not throw anything, we have to introduce that ourselves:

async function getUser(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error("User not Found!");
  }
  const json = await response.json();
  return json.data;
}

On the other hand, response.json() will throw if the response body is not valid JSON.

In the event handler, we need a try...catch around getUser:

document.querySelectorAll("button[data-url]").forEach((button) =>
  button.addEventListener("click", async (event) => {
    try {
      const user = await getUser(event.target.dataset.url);
      userElement.innerHTML = `
    <h2>${user.first_name} ${user.last_name}</h2>
    <img alt="${user.first_name} ${user.last_name}" src="${user.avatar}"/>
    `;
    } catch (error) {
      alert(error);
    }
  })
);