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