Javascript json获取错误处理,然后给它一个可选字符串

Javascript json获取错误处理,然后给它一个可选字符串,javascript,arrays,json,fetch,Javascript,Arrays,Json,Fetch,如果无法连接到获取url,是否可以提供默认的替代JSON字符串 const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) 您可以使用try/catch块 让我们回应3; 试一试{ Response3=等待获取`https://example.com/match/get?_=&id=${matchlist[2].id}`; 如果!回答3.好的 抛出新的ErrorResp

如果无法连接到获取url,是否可以提供默认的替代JSON字符串

const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`)
您可以使用try/catch块

让我们回应3; 试一试{ Response3=等待获取`https://example.com/match/get?_=&id=${matchlist[2].id}`; 如果!回答3.好的 抛出新的ErrorResponse3.statusText; }抓住e{ 响应3={ 道具:“默认json” } }
//在这里处理Response3数据。您可以像承诺一样使用fetch,在fetch末尾添加.然后读取响应

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
      }
    })
  }
})
您可以在此处了解有关承诺的更多信息:

给您

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();
如果你需要任何解释,或者这不是你要问的,请评论我的回答