Fetch – the wrong way
fetch in JavaScript is awesome.
But, you may have something like this sprinkled throughout your code:
const res = await fetch('/user')
const user = await res.json()
While nice and simple, this code has a number of issues.
You could say “oh, yeah, handle errors”, and rewrite it like this:
try {
const res = await fetch('/user')
const user = await res.json()
} catch (err) {
// Handle the error
}
That is an improvement, certainly, but still has issues.
Here, we’re assuming user is in fact a user object… but that assumes that we got a 200 response.
But fetch does not throw errors for non-200 statuses, so you could have actually received a 400 (bad request), 401 (not authorized), 404 (not found), 500 (internal server error), or all kinds of other issues.