0
votes

Manutention d'erreur JSON

est-il possible de donner une chaîne JSON par défaut (alternative) si elle ne peut pas se connecter à la Fetch URL? xxx


0 commentaires

3 Réponses :


0
votes

Vous pouvez utiliser un essayer code> / bloc code> bloc

p>

let Response3;

try {
  Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`);
  if (!Response3.ok)
    throw new Error(Response3.statusText);
} catch (e) {
  Response3 = {
    prop: 'default json'
  }
}
// do something with the Response3 data here.


0 commentaires

-1
votes

Vous pouvez utiliser une promesse comme une promesse en ajoutant .Chen code> à la fin de la recherche et de la lecture de la réponse.

const Response3 = await fetch(url).then((response) => {
  //Check the response coming back to see if it was successful
  if (response.status === 200) {
    return response.json(); //returns data returned from call
  } else {
    // if not successful, make your other call
    fetch(otherUrl).then(res2 => {
      if (res2.status === 200) {
        return response.json(); //if your second call was successful, return the data
      }
    })
  }
})


0 commentaires

0
votes

Ici vous allez

async function checkResponse(url) {
      const Response3 = await fetch(url);
      // thats mean pleas check the status of Response3 if it is equal to 404 (cannot connect to server)
      // otherwise put the same response (or the data you want like: Response3,players)
      let Response4 =
        Response3.status === 404 ? 'Cannot connect to the server' : Response3;
      /* 
      // or if you like if statment
      let Response4 = Response3;
      if (Response3.status === 404) {
        Response4 = 'Cannot connect to the server';
      }
    */
      console.log(Response4);
    }
    checkResponse();


0 commentaires