Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Handle error when Promise is not fulfilled

I am trying to pull data from cache when app is offline and print out "No internet connection" but I am keep failing to catch an error when Promise is not fulfilled i.e. when app is offline. I've tried try/catch, response.catch and other logics but none of them worked. Could someone point me to the right direction? What is wrong with my code?

grad = input.value ? input.value : "zagreb";


try{
  let response = await fetch(
    `https://api.weatherapi.com/v1/forecast.json?key=bdbf7197ebc24abbb15104932220407&q=${grad}&aqi=yes`)
  //console.log("API-response: ", response)

  
  let data = await response.json();
  

  if (data.error) {
      document.getElementById("content").innerHTML = `<p id="nodata">No data for the requested city</p>`;
  } 
  else {
      dayTime(data);

      let rezultat = `<p id="location">${data.location.name}, ${data.location.country}, ${data.location.localtime}</p><ul id="lista">`;
          rezultat += weatherConditions(data);
          rezultat += temperatura(data);
          rezultat += cloudCover(data);
          rezultat += uvZracenje(data);
      rezultat += "</ul>";
      document.getElementById("content").innerHTML = rezultat;
  }
}

catch{
let cashed = ``;
data.cache = response.headers.has("cache");
console.log("kesiran data: ", data.cache)
if(data.cache){
  
cashed = document.getElementById("content").innerHTML = `<p id="nointernet">No internet connection</p>`;
}

}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Attach catch to fetch() itself, from there you can set a flag or whatever that there is an error, the response will be undefined so you can check that too.

async function myFunc()
{
  console.log("fetching");
  let response = await fetch(`https://whatever.com`)
    .catch(er => console.error("error", er));

  console.log("API-response: ", response)

}

myFunc();
​.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important}

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda