How to catch errors with ApolloProvider globally

545 Views Asked by At

I'm trying to catch all my graphQLErrors with the onError method from apollo client. My goal is to have only one catch block for all of my API calls.

const errorLink = onError(({ graphQLErrors, networkError ,operation}) => {
   if (graphQLErrors && graphQLErrors?.length > 0) {
     catchError((e) => handleError(e))
   } else if (networkError) {
     console.log(`[Network error]: ${networkError}`)
   }
})

The current behavior is: If I do not catch each error inside the component that made the API call the default error page appears with the error

The desired behavior: The default error page will never appear (the error will be handled inside onError method)

1

There are 1 best solutions below

1
On

Wrap your app in an Error Boundary component

From the docs, this is an example of a react component that catches and prints errors. You can respond to errors in any way you want.

Unfortunately there's currently no hook that catches issues, you must use the class function lifecycle method componentDidCatch.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}