TransWikia.com

function stops when fetch() fails

Stack Overflow Asked by uncannyorange on February 2, 2021

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.

2 Answers

Is there a way I can suppress the error?

You should wrap your function that may cause the error in try...catch.

const fetch = (isFine) => new Promise(resolve => {
  if(isFine) 
    resolve("Normal data");
  else
    throw new Error("Error msg...!");
});

const myFunction = async (isFine) => {
  try {
    const response = await fetch(isFine);
    console.log(response);
  }
  catch(err) {
    console.log("Oops..." + err.message);
  }
}

myFunction(true);
myFunction(false);

Answered by Phong on February 2, 2021

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);
}

Answered by Tan Yi Jing on February 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP