Skip to content
Advertisement

function stops when fetch() fails

so I have a normal thing you would do to find if a file exists and proceed accordingly:

let response = await fetch(url);
if (response.ok) {
  //it exists
} else {
  //it doesn't
}

Problem is, of course, if it fails it gives me a TypeError: Failed to fetch and my function stops.
Is there a way I can suppress the error?
I cannot change from a fetch function, i’ve tried everything else and fetch is the best option in my context.
Thanks in advance.

Advertisement

Answer

You will need to implement try and catch and it is quite easy to implement it. You can have a look at Try and Catch Documentation

Have a look at the sample code below

try {
  let response = await fetch(url);
}
catch(err) {
  alert("Error Message : " + err.message);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement