Search code examples
angulargraphqlapolloapollo-serverexpress-graphql

How to handle error using apollo client in angular for graphql?


Below is my code . I have been trying to somehow link the error variable to GraphQL Module . Kindly provide a way to achieve that .

import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { onError } from 'apollo-link-error';

const uri = 'http://localhost:3000/graphql'; 

const error = onError(({ graphQLErrors, networkError }) => { // need help on linking this with graphql module
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

// <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink) {
  return {
    link: httpLink.create({ uri }),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  exports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

I need help on linking error with GraphQL Module . How can I do that? Thanks in advance .


Solution

  • Apollo links are composable units. Each link is a function that takes the operation as an argument and returns an observable. Apollo links will work just like a middleware that might transform a request and its result.

    You can combine the error link to the main module as

    export function createApollo(httpLink: HttpLink) {
      return {
        link: error.concat(httpLink.create({ uri })),
        cache: new InMemoryCache(),
      };
    }