我正在用JavaScript编写天气应用程序,你可以猜到有很多API请求。所以在这里我向API发出请求,然后将返回我的城市形象。城市来自用户输入。
async getCityImage(city) {
console.log(city, 'getCityImage');
await fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`)
.then(res => res.json())
.then((res) => {
this.imageUrl = res.photos[0].image.mobile;
});
}
}
问题是用户输入可能不合适,当然API会返回这样的错误
> GET https://api.teleport.org/api/urban_areas/slug:munchen/images/ 404
(未找到)
For example there are some cities which names are separated by hyphen
堪萨斯城,危地马拉城等...
所以我想处理错误,以便错误不会影响UI,但是再次发出这样的请求,然后返回答案`
获取https://api.teleport.org/api/urban_areas/slug:$ {city} -city / images /
我试图通过嵌套请求来实现它,但它不起作用
你可以使用这样的东西
async getCityImage(city) {
console.log(city, 'getCityImage');
await fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`)
.then(res => res.json())
.then((res) => {
this.imageUrl = res.photos[0].image.mobile;
})
.catch((e) => { //do something with error});
}
}
你可以使用这样的try catch语句:
async getCityImage(city) {
let res;
try {
res = await fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`);
return res.photos[0].image.mobile;
} catch(e) {
// here you can do something when the request fails
res = await trySomethingElse();
return res
}
}
这是我的解决方案,可能不是最好的,但在这种情况下,它可以帮助我。
getCityImage(city, hyphen) {
console.log(city, 'getCityImage');
return fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`)
.then(res => res.json())
.then((res) => {
if (res.status === 404)
return fetch(`https://api.teleport.org/api/urban_areas/slug:${city}-city/images/`)
.then(res => res.json());
else
return res;
})
.then((res) => {
this.imageUrl = res.photos[0].image.mobile;
})
.catch((err) => {
console.log(err, 'erroroooooooorr');
});
}
你可以这样做 -
本机提取API - 更新
(async () => {
async function getCityImage(city) {
let response = await fetch(`https://api.teleport.org/api/urban_areas/slug:${city}/images/`);
if (response && response.status && response.status === 200) {
const json = await response.json();
return json.photos[0].image.mobile;
} else {
throw Error(`got error, error code - ${response.status}`);
}
}
try {
console.log(await getCityImage("london"));
console.log(await getCityImage(null));
} catch (error) {
console.error(error);
}
})();