I can't handle the error after the first fetch method in the code below
As I click on the btn with the network status set to offline, instead of getting the error that I have defined in throw new error
which is Your internet connection is lost
, I get Failed to fetch
message and I don't know where is the problem
It's like it doesn't even execute the if condition in the 10th line after the first fetch
And here is the code itself:
const whereAmI = async function () {
try {
// Geolocation
const coords = await getCoords();
// Reverse geocoding
const res1 = await fetch(
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords[0]}&lon=${coords[1]}`
);
if (!res1.ok) throw new Error('Your internet connection is lost');
const countryData = await res1.json();
// Country data
const res2 = await fetch(
`https://restcountries.com/v3.1/name/${countryData.address.country}`
);
const [data] = await res2.json();
renderCountry(data);
} catch (err) {
console.error(`${err.message} `);
renderError(`Something went wrong ${err.message} Try again`);
}
};
btn.addEventListener('click', whereAmI);