JS: how to handle error from nested then() in outer catch block?

33 Views Asked by At

I am following a tutorial about handling errors of fetch() but now it turns to be learning handling errors. This is the code I wrote. I wish to handle all errors inside the outer catch:

        fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: {
        name: this.enteredName,
        rating: this.chosenRating
      }
    }).then(response => {
      if (response.ok) {
        //...
      } else {
        response.json().then(json => {
          const msg = 'Custom error handling: could not save data' +
            ', error code: ' + response.status + ', error: ' + json.error;
          throw new Error(msg);
        }).catch(e => {
          console.log('catch1:');
          throw e;
        });
      }
    })
      .catch(err => {
        console.log('catch2:');
        this.error = err.message;
      });

The problem with this code is that the outer catch cannot catch the error from inner then block, even through I rethrow it in inner catch block. What would be a clean and elegant way to achieve this? Please dont change response.ok because I wish to learn the solution for this exact situation.

1

There are 1 best solutions below

4
Ritik Banger On
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: this.enteredName,
    rating: this.chosenRating
  })
}).then(response => {
  if (response.ok) {
    //...
  } else {
    return response.json().then(json => {
      const msg = 'Custom error handling: could not save data' +
        ', error code: ' + response.status + ', error: ' + json.error;
      throw new Error(msg);
    }).catch(e => {
      console.log('catch1:');
      return Promise.reject(e); // Use return Promise.reject() to propagate the error
    });
  }
}).catch(err => {
  console.log('catch2:');
  this.error = err.message;
});

By using return Promise.reject(e); in the inner catch block, you ensure that the rejected promise is propagated down the chain, allowing the outer catch block to handle the error. This way, you don't need to rethrow the error in the outer catch block, and it will be caught by the outer catch block as intended.