Tengo un problema cuando arrojo un error en el primer bloque .then, el bloque .catch no detecta el error que se arrojó. Simplemente muestra el error en el bloque .catch.
Aquí hay un enlace al código: 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} 🔥 `), renderError(`Something went wrong ${err.message}. Try again!`); }) .finally(fade => { countriesContainer.style.opacity = 1; }); }; btn.addEventListener('click', function () { getCountryData('portu=gal'); });Cuando no se encuentra el país, response.ok es verdadero pero el dato[0] no está definido. Eso es porque response.json da {status:404,message:”not found”} . Por lo tanto, la verificación de si se encuentra el país debe cambiar a
If (data.status === 404) throw new Error(“not found”)