Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch React Native fetch error without halting the app with red screen

Tags:

react-native

I am making a React Native function that pulls the HTML of a webpage. It works fine if the URL exists and I receive a 200 status code. However, when I put a wrong url in there (something that would receive a 404 error), it displays a red screen that says "Network request failed." I'd like to catch the error without the whole app halting and display an alert to the user. How can I go about doing that?

    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;
       });
    }
like image 794
Josh Avatar asked Jul 12 '17 20:07

Josh


1 Answers

You can use Alert component from react-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 toast like on Android than alert.

like image 133
Akbar Rachman Gifari II Avatar answered Oct 21 '22 06:10

Akbar Rachman Gifari II