javascriptasynchronouserror-handlingtry-catchthrow

Error Handling in Asynchronous JavaScript using throw


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?


Solved:

The promise returned by fetch() always resolves if the HTTP request completes, it does not matter if there is an HTTP status error. In the first argument of the then() block we are handling HTTP errors. The promise will reject when there is a network error, which is unrelated to the HTTP status. In this case we must handle the reject scenario with the second argument in then().


Solution

  • 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.