json извлеките обработку ошибок и передайте ей альтернативную строку - PullRequest
0 голосов
/ 03 апреля 2020

Можно ли указать стандартную (альтернативную) строку JSON, если она не может подключиться к URL-адресу выборки?

const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`)

Ответы [ 3 ]

0 голосов
/ 03 апреля 2020

Вы можете использовать выборку как обещание, добавив .then в конец выборки и прочитав ответ.

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

Подробнее об обещаниях можно узнать здесь: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

0 голосов
/ 03 апреля 2020

Здесь вы go

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 голосов
/ 03 апреля 2020

Вы можете использовать try / catch блок

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...