Closed moonwave99 closed 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:
!response.ok
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.
response.json()
In the event handler, we need a try...catch around getUser:
try...catch
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); } }) );
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: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
aroundgetUser
: