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:
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With