skip to Main Content

I’m having some problems trying to understand the following code in an excercise concerning error handling:

const getSuggestions = () => {
  const wordQuery = inputField.value;
  const endpoint = url + wordQuery;

  fetch(endpoint, {cache: 'no-cache'})
  .then(response => {
    if(response.ok) {
      return response.json();
    } throw new Error('Request failed!');
  }, networkError => {
    console.log(networkError.message);
  })
}

My question is: Why do we catch errors for two times here? One time using throw new Error, and one time by adding a second argument networkError into .then()? Are they catching the same error and thus redundant?

How does it look if we use try...catch... here?

3

Answers


  1. Because fetch will only throw an error on network errors, not on error status-codes like 404.

    In this snippet Someone checked wether the response was 200 and if not added a “custom” error using throw.

    Login or Signup to reply.
  2. This is equivalent code, but hopefully more understandable

      fetch(endpoint, {cache: 'no-cache'})
      .catch(networkError => {
          console.log(networkError.message);
          return 'networkError'
       })
      .then(response => {
         if (response == 'networkError') return;
         if (response.ok) {
            return response.json();
         } else {
            throw new Error('Request failed!');
         }
      })
    
    Login or Signup to reply.
  3. The 2 error mechanisms are dealing with different types of errors:

    1. if(!response.ok) deals with http responses from the server for http 4xx and 5xx response statuses. The call reached an http server and it responded.

    2. The networkError => { is for errors arising before even reaching a server, possibly even reaching the network.

    They are very different, managed differently.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search