使用 $fetch Javascript 的 HTTP Ajax 调用中的错误处理



我试图处理HTTP ajax调用中与网络相关的问题。因此,我暂时停止了 IIS 中相应 API 的服务,并尝试调用关闭的 API -http://localhost:1000/GetData

fetch("http://localhost:1000/GetData")
.then(handleErrors)
.then(function(response) {
return response.Json();
}).catch(function(error) {
console.log(error);
});

我也尝试了以下代码

fetch("http://localhost:1000/GetData")
.then(response => {
if(response) {
if (response.status === 200) {
alert('Super');
return response.json();
} else {
alert('Hai');
return '';
} 
} else {
alert('Oooops');
return '';
}
})
.catch(function(error) {
console.log(error);
});

但是它失败了,直接击中了捕获块而没有触发任何alert并且抛出了一个错误。此外,response.json();在成功块中,我不知道它是如何执行的。

TypeError: response.json is not a function
Stack trace:
onFetchError/<@http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13

请协助我如何检查状态代码以及如何处理网络错误(即网络不可用404等(

推荐网站: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

基于Github上的此问题,您可以尝试在catch块中识别错误类型。因此,这样的事情可能适用于您的情况:

fetch("http://localhost:1000/GetData")
.then(response => {
alert("Super");
return response.json();
})
.catch(err => {
const errStatus = err.response ? err.response.status : 500;
if (errStatus === 404){
// do something
} else {
// do another thing
}
});

最新更新