javascriptexceptionapolloapollo-clientinternet-connection

How to check that ApolloError is caused by client internet connection?


ApolloError has networkError prop, but it is set when server responds with 4** or 5** status code.

And how to check that the problem is caused by bad internet connection?

try {
   apolloClient.query(someQuery)
} catch (error) {
  if (isInternetConnectionError(error)) { // how to check this?
    Alert.alert('Please check your internet connection!')
  } else {
    logException(error);
  }
}

Solution

  • Seems that there is no good way to get that (nice work Apollo), but this is the exact error state that comes when there is no internet:

    export const isNetworkError = (error: unknown) => {
      return (
        error instanceof ApolloError &&
        error.message === 'Network request failed' &&
        error.graphQLErrors.length === 0 &&
        error.clientErrors.length === 0 &&
        error.networkError &&
        Object.keys(error.networkError).length === 0
      );
    };
    

    Relevant for "@apollo/client": "3.4.7"

    Or here is much shorter version that should work:

    export const isNetworkError = (error: unknown) => {
      return (
        error instanceof ApolloError &&
        error.message === 'Network request failed'
      );
    };