17
votes

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.

2

2 Answers

6
votes

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.

-1
votes

A server error might mean that there's no data object coming from the server so there's also no error message available.

Let's say you query some user data so that the result object would be data.user. Then you want to test:

if (data.loading !== true && data.user === undefined) {
   /* handle the error here */
}

If you don't want to see the error messages, you can add options to your query:

graphql(query, {
  options: {
    errorPolicy: 'ignore'
  }
})