我的问题不同于 React Native fetch() Network Request Failed ,我不是在为 http 或 https 苦苦挣扎,我只是想在请求因互联网连接、错误的 API 等原因而失败时向用户提供一个很好的错误,而不是得到 react native 错误。
我有一个表单,想将它发送到服务器并获得响应,所以我这样写:
submitForm = async () => {
fetch("www.somewhere.com", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(some_data)
})
.then((response) => response.json())
.then((responseJson) => {
// do something
})
.catch((error) => {
this.setState({server_error: "request failed try again."});
});
};
但是我的 catch 似乎不能正常工作,因为如果请求失败,我会从 react native 中得到一个错误,如下所示: 在生产中,它只是跳出应用程序,我该如何避免这种情况?
最佳答案
不知道这是否会解决您的问题,但是您的提取代码会尝试创建 JSON,即使响应是 404,例如。
在创建JSON之前还需要检查响应是否OK
submitForm = async () => {
fetch("www.somewhere.com", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(some_data)
})
.then((response) => {
if(response.statusText == "OK" && response.status >= 200 && response.status < 300) {
return response.json()
} else {
throw new Error("Server can't be reached!")
}
})
.then((json) => {
console.log("hooray! we have json!")
console.log(json)
})
.catch((error) => {
console.log("error fetching data")
console.log(error)
console.log(error.message) // Server can't be reached!
this.setState({server_error: "request failed try again."});
});
};
关于javascript - 如何处理网络请求失败错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54649525/