我正在用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 /
我试图通过嵌套请求来实现它,但是它不起作用
答案 0 :(得分:0)
您可以使用类似的东西
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});
}
}
答案 1 :(得分:0)
您可以使用如下的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
}
}
答案 2 :(得分:0)
您可以执行以下操作-
本地获取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);
}
})();
答案 3 :(得分:0)
这是我的解决方案,可能不是最好的方法,但是在这种情况下,它可以帮助我。
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');
});
}