Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle network request failed error?

my problem differs from React Native fetch() Network Request Failed, I'm not struggling with http or https, I just want to provide a nice error to the user if the request fails due to the internet connection, wrong API, etc. instead of getting react native error.

I have a form and want to send it to a server and get a response so I wrote this:

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

But It seems that my catch doesn't work correctly because if the request fails I get an error from react native like this: enter image description here and in production, it just jumps out of the app, how can I avoid this?

like image 288
Reza Shoja Avatar asked Feb 12 '19 11:02

Reza Shoja


People also ask

What does Error network request failed mean?

Network request failed, this error occurs usually when api call failed or you have some internet issue. In android emulator, sometimes this error comes during debug mode but works fine when app use in release mode.

How do I fix resolve network request failed in react native?

It's just that simple! Start your app as usual but don't forget to give an IP address and a port, this will help you solve the Network Request Failed error. And on your mobile app, make sure to use the correct URL in your request.

What is network request?

A network request is an HTTP request from your mobile app to a server-side application. The iOS Agent detects network requests when the underlying implementation is handled by the NSURLConnection or NSURLSession classes.


1 Answers

Don't know if this will solve your problem, but your fetch code tries to create JSON, even if the response is a 404, for example.

You also need to check if the response is OK before creating 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."});
  });
};
like image 130
Kokodoko Avatar answered Oct 29 '22 09:10

Kokodoko