Handling Apollo errors on the component side
As you already pointed out, you could use the apollo-link-error
package
Link.
If you also use react-router-dom
for routing between pages, it is possible to use the browser history or the Redirect component to redirect to an error page with a state object (routing history). The state object contains the error that you would like to show.
The setup could look like this:
- Create browser history
import { History, createBrowserHistory } from 'history';
/* If using Typescript, you can make this object Readonly as follows */
export type ReadonlyBrowserHistory = Readonly<History>
const browserHistory: ReadonlyBrowserHistory = createBrowserHistory();
export default browserHistory;
- Add Router with browser history (w/ option to make history properties readonly)
import browserHistory from './browserHistory'
import apolloClient from './apolloClient'
...
ReactDOM.render((
<ApolloProvider client={apolloClient}>
<Router history={browserHistory}>
<App />
</Router>
</ApolloProvider>
), document.getElementById("root"));
- add link with routing to apollo client
import browserHistory from './browserHistory'
const errorLink = onError(({ networkError, graphQLErrors }) => {
if (graphQLErrors) {
browserHistory.push("/error", { errors: graphQLErrors });
}
else if (networkError) {
browserHistory.push("/error", { errors: networkError });
};
});
const httpLink = new HttpLink({
uri: httpUri
});
const httpLinkWithErrorHandling = ApolloLink.from([
errorLink,
httpLink,
]);
const apolloClient = new ApolloClient({
link,
...
});
export default apolloClient;
- The error page can retrieve the errors from the route location prop
const ErrorPage = ({ location: { state } }) => {
console.log(state);
return (<div>error page</div>)
};