繁体   English   中英

如何处理网络请求失败错误?

[英]how to handle network request failed error?

我的问题与React Native fetch() Network Request Failed 不同,我并没有在 http 或 https 上挣扎,如果由于互联网连接、错误的 API 等请求失败,我只想向用户提供一个很好的错误。得到反应本机错误。

我有一个表格,想把它发送到服务器并得到回复,所以我写了这个:

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."});
  });
};

但似乎我的捕获无法正常工作,因为如果请求失败,我会从 react native 收到如下错误: 在此处输入图片说明 而在生产中,它只是跳出应用程序,我该如何避免这种情况?

不知道这是否能解决您的问题,但您的 fetch 代码会尝试创建 JSON,即使响应是 404,例如。

您还需要在创建 JSON 之前检查响应是否正常

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."});
  });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM