当Promise未实现时处理错误



我正试图从缓存中提取数据,当应用程序离线并打印出"没有互联网连接";但我一直未能捕捉到一个错误时,承诺不履行即当应用程序离线。我试过try/catch, response。Catch和其他逻辑都不起作用。有人能给我指个正确的方向吗?我的代码有什么问题?

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

catch附加到fetch()本身,从那里你可以设置一个标志或任何有错误的东西,response将是undefined,所以你也可以检查。

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}