DEV Community

[Comment from a deleted post]
Collapse
 
tqbit profile image
tq-bit

Hello MJ,

thank you for your reply.

I've got to agree, fetch is a little underrepresented in the docs. I'm keeping a small template to boilerplate for several usecases in Notion, perhaps you could make use if it as well.

notion.so/Browser-s-fetch-API-73e8...

If you /really/ wanted to inspect server response statuses in a classic fetch() implementation could you not do this in the .catch() function - ie without the need for asynch/await

As far as I understand, .catch() is fired when an error with the executed code occurs.

Say you try and resolve your fetched data stream to json with response.json(), but there really is no body that could be converted. In that case, your .catch() block will throw you an error like this:

SyntaxError: Unexpected token U in JSON at position 0

You could alternatively try and handle the status inside the first .then() - block, like it's shown in this (google docs blog)[developers.google.com/web/ilt/pwa/...]. After all, choosing between .then and async / await is also a matter of personal or team preference.

fetch('examples/example.json')
.then(function(response) {
  if (!response.ok) {
    // if (response.status === 400) {/* ... */}
    // if (response.status === 401) {/* ... */} 
    // ...
  }
  // Do stuff with the response
})
.catch(function(error) {
  console.log('Looks like there was a problem: \n', error);
});
Enter fullscreen mode Exit fullscreen mode
 
mjoycemilburn profile image
MartinJ

Gosh - you're absolutely right. It's there in the Mozilla docs too - "the fetch() method ... returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status." In bold text too! It's funny how your eye can just skate over something like that when you're concentrating on something else.

Control ends up in the .catch with a JSON error, exactly as you said. But, hey, all isn't lost as it's easy enough to pick up response.status in the first .then() and redirect as in your try block.

As you say, it's all a matter of style but, to me, try/catch blocks always look a bit desperate!

I like your boiler-plate examples. I'll make a note of the abort template.

Regards, MJ