Catch fetch error in service helper and alerting users in main React Native app

Hello,

I am simply looking for best practice where I have a service helper that calls the fetch API and on error (status is not 200) I would like to alert the user with a message he / she can retry / cancel without the main React Native app crashing with a red screen.

I found this article on StackOverflow that seems to give the answer, but I wanted to hear if there is a better way to do this.

Thank you as always,

you can use async/await

async doSomething() {
  try {
    let response = await fetch('someurl');
    let result = await response.json();
    // do something with result
  } catch(e) {
    alert('error');
  }
}

Thank you @notbrent, let me be more specific.

Here is a function in my service helper JS:

export const downloadBubbles = () => {
    const endpoint = `${Config.AWS_UPLOAD_TRANSLATE_LAMBDA_BASE_ENDPOINT}/derivative/downloadBubbles`;
    const api = '/demo/derivative/downloadBubbles';
    logRequestInfoToConsole(api, 'GET', endpoint, null);
    return fetch(endpoint, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    })
        .then((res) => {
            logResponseInfoToConsole(api, 'GET', res);
            if (res.ok) {
                return res.json();
            } else {
                throw Error('Failed to download bubbles!');
            }
        })
        .catch((err) => {
            console.error(err);
        });
};

The main RN app calls the function this way:

try {
  const downloadURNsResult = await downloadBubbles();
  // do something with result
} catch (err) { 
   Alert.alert('Application Error');
}

My issue is that the main RN app crashes with red screen displaying the console.error message. I’m trying to redirect this to the RN Alert.alert.

Thank you,

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.