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;
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With