I’m trying to throw an error from within a setContext
call and have that error caught by the onError
link within Apollo. The problem is that it seems onError
is never triggered when the error is thrown.
export async function createApolloClient(request: Request) {
const httpLink = ApolloClient.createHttpLink({
uri: apiConfig.graphqlUri,
});
const authLink = ApolloLinkContext.setContext(async (_, { headers }) => {
const session = await sessionStorage.getSession(
request.headers.get('Cookie'),
);
// This can throw an error that I want to be caught by `onError`
const accessToken = await authenticate(request, session, headers);
return {
headers: {
...headers,
Authorization: accessToken ? `Bearer ${accessToken}` : '',
},
};
});
const errorLink = onError(
({ graphQLErrors, networkError, operation, forward }) => {
// This is never called and instead the error from `createContext` is thrown and not handled.
return forward(operation);
},
);
return new ApolloClient.ApolloClient({
ssrMode: true,
cache: new ApolloClient.InMemoryCache({ addTypename: false }),
link: ApolloClient.ApolloLink.from([
authLink,
errorLink,
httpLink,
]),
});
}
It seems like throwing an error from within setContext
doesn’t trigger the errorLink
at all. Instead, the error from setContext
is simply thrown without being handled.
For more context, I’m trying to get this working in Remix (SSR).