-1

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

Here is the image of the code

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);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    Requesting `https://nominatim.openstreetmap.org/reverse?format=json&lat=54&lon=45` directly via my browser address bar, I don't see any CORS headers in the response - so your request probably fails with a CORS error ...? – CBroe Aug 30 '23 at 07:33
  • @CBroe - What is CORS? And what should the value be exactly? – Mehrshad Cheshm Khavari Aug 30 '23 at 07:35
  • https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header – derpirscher Aug 30 '23 at 07:45
  • @CBroe I actually found this api on [github public apis](https://github.com/public-apis/public-apis) which is called [Nominatim](https://nominatim.org/release-docs/latest/api/Overview/) and in github it has marked the CORS as yes – Mehrshad Cheshm Khavari Aug 30 '23 at 07:57
  • So what you are saying is, that you are running this code while not connected to the internet? If you want to detect _that_, you will probably need to start with a try/catch, as in https://stackoverflow.com/q/73977372/1427878 Or you just directly ask the browser whether its got a working connection or not, https://stackoverflow.com/q/189430/1427878 – CBroe Aug 30 '23 at 08:04

0 Answers0