Home > Enterprise >  Promises with Fetch and Throwing Errors
Promises with Fetch and Throwing Errors

Time:01-01

I am having a problem when I throw an error in the first .then block, the .catch block does not catch the error that has been thrown. It just displays the error in the .catch block.

Here is a link to the code: Code Pen Example

    const getCountryData = country => {
  // Country 1
  fetch(`https://restcountries.com/v2/name/${country}`)
    .then(response => {
      if (!response.ok)
        throw new Error(`Country not found (${response.status})`);

      return response.json();
    })
    .then(data => {
      renderCountry(data[0]);
      const neighbor = data[0].borders[0];
      if (!neighbor) return;

      // Country 2
      return fetch(`https://restcountries.com/v2/alpha/${neighbor}`);
    })
    .then(response => {
      if (!response.ok)
        throw new Error(`Country not found (${response.status})`);
      return response.json();
    })
    .then(data => {
      renderCountry(data, 'neighbour');
    })
    .catch(err => {
      console.error(`${err}            
  • Related