Catch React Original fetch error without stopping the red screen application

I am creating a React Native function that extends the HTML page of a web page. It works fine if the URL exists and I get a status code of 200. However, when I put the wrong URL (something that gets a 404 error), it displays a red screen that says: "Network error." I would like to catch an error without stopping the entire application and display a warning to the user. How can i do this?

    fetchEvents() {
       fetch('http://www.wrongurl.com', {
         method: 'GET',
         redirect: 'follow'
       })
       .then(function(response) {
           if (response.status == 200) {
               let responseText = JSON.stringify(response.text());
               console.log(responseText);
           }
         else throw new Error('HTTP response status not code 200 as expected.');
       })
        .catch(function(error) {
           console.error(error);
           return error;
       });
    }
+4
source share
3 answers

Here's how I solved it, making graceful errors that don't break the application using promises:

In my API service class:

  fetchEvents() {
    let thisCurrentAPIService = this;

    return new Promise(
      function (resolve, reject) {
        fetch('http://www.wrongurl.com');
        .then(
          function(response) {
            if (response.ok) {    
              let responseText = JSON.stringify(response.text());
              console.log(responseText);
            }
            else {
              reject(new Error(`Unable to retrieve events.\nInvalid response received - (${response.status}).`));
            }
          }
        )
        .catch(
          function(error) {
            reject(new Error(`Unable to retrieve events.\n${error.message}`));
          }
        );
      }
    ); 
  }

React. , .

      this.state.apiService.fetchEvents()
      .then(
      function (value) {
        console.log('Contents: ' + value);
      },
      function (reason) {
        Alert.alert(`${reason.message}`);
      });
+1

console.warn( " " );

dev, . , , . : .

+1

You can use the Alert component from native-native.

fetchEvents() {
   fetch('http://www.wrongurl.com', {
     method: 'GET',
     redirect: 'follow'
   })
   .then(function(response) {
       if (response.status == 200) {
           let responseText = JSON.stringify(response.text());
           console.log(responseText);
       }
     else throw new Error('HTTP response status not code 200 as expected.');
   })
    .catch(function(error) {
       Alert.alert(error);   // Using this line
   });
}

But I prefer using toasts, like on Android, than alerts.

0
source

Source: https://habr.com/ru/post/1681301/


All Articles