Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo Client (React): Handling unexpected errors

I have been reviewing the Apollo documentation but I do not see information of how to go about handling server errors in the Apollo client.

For example, suppose that the server either:

  • Times out
  • Becomes unreachable
  • Unexpectedly fails

How should this be handled in the client? Apollo currently fails with errors such as:

Unhandled (in react-apollo) Error: GraphQL error: Cannot ...

I'd like to avoid this happening and handling these errors. How can I do so using React Apollo?


For reference:

I am currently using React-Apollo and Redux.

like image 843
dipole_moment Avatar asked Apr 27 '17 00:04

dipole_moment


People also ask

Does Apollo client throw an error?

Throwing errorsApollo Server throws errors automatically when applicable. For example, it throws a GRAPHQL_VALIDATION_FAILED error whenever an incoming operation isn't valid against the server's schema. Your resolvers can also throw errors in situations where Apollo Server doesn't do so automatically.

How do you handle errors in Apollo GraphQL?

When a network error occurs, Apollo Client adds it to the error. networkError field returned by your useQuery call (or whichever operation hook you used). You can add retry logic and other advanced network error handling to your application with Apollo Link.

How do you handle error in Usemutation?

Calling the mutate function returned by the hook returns a Promise. If the request is successful, the Promise will resolve to a response object that includes the data returned by the server. If the request fails, the Promise will reject with the error.

Does Apollo client need react?

While you don't need React or another front-end framework just to fetch data with Apollo Client, our view layer integrations make it easier to bind your queries to your UI and reactively update your components with data.


1 Answers

Errors are passed along in the error field on your component props: http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error

function MyComponent({ data }) {
  if (data.error) {
    return <div>Error!</div>;
  } else {
    // ...
  }
}

export default graphql(gql`query { ... }`)(MyComponent);

That message is printed if we detect that there was an error and the error field was not accessed in the component.

You could write a higher-order component to handle errors in a generic way, so that you can wrap all of your components with that.

like image 153
stubailo Avatar answered Oct 10 '22 16:10

stubailo