Skip to content

Instantly share code, notes, and snippets.

@clarencenpy
Last active April 12, 2019 02:27
Show Gist options
  • Save clarencenpy/960603dc493a6158e74fe5bb1ba81f03 to your computer and use it in GitHub Desktop.
Save clarencenpy/960603dc493a6158e74fe5bb1ba81f03 to your computer and use it in GitHub Desktop.
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: '<your graphql endpoint>',
// Apollo Boost allows you to specify a custom error link for your client
onError: ({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
// handle errors differently based on its error code
switch (err.extensions.code) {
case 'UNAUTHENTICATED':
// old token has expired throwing AuthenticationError,
// one way to handle is to obtain a new token and
// add it to the operation context
const headers = operation.getContext().headers
operation.setContext({
headers: {
...headers,
authorization: getNewToken(),
},
});
// Now, pass the modified operation to the next link
// in the chain. This effectively intercepts the old
// failed request, and retries it with a new token
return forward(operation);
// handle other errors
case 'ANOTHER_ERROR_CODE':
// ...
}
}
}
},
});
@techyrajeev
Copy link

techyrajeev commented Jul 11, 2018

@clarencenpy How should getNewToken() be implemented? getNewToken is an async call it seems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment