admin管理员组

文章数量:1315823

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
  • Bees 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.

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
  • Bees 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.

Share Improve this question asked Apr 27, 2017 at 0:42 dipole_momentdipole_moment 5,8744 gold badges42 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6 +50

Errors are passed along in the error field on your ponent props: http://dev.apollodata./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 ponent.

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

A server error might mean that there's no data object ing 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'
  }
})

本文标签: javascriptApollo Client (React) Handling unexpected errorsStack Overflow