Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use import { onError } from 'apollo-link-error' in angular to handle all errors

Below is my setup code for apollo angular:

providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => {
        return {
          cache: new InMemoryCache(),
          link: httpLink.create({
            uri: AppSettings.API_ENDPOINT

          })
        }
      },
      deps: [HttpLink]
    }
  ],

I want to use below :

const link = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

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

How can I link this so I am able to get errors in the console?

like image 384
Sunny G Avatar asked Aug 16 '19 12:08

Sunny G


2 Answers

Here is how I use 'apollo-link-error' to handle graphQL errors and Network errors. I have created a separate module called apollo-clients-module.ts and imported it on app.module.ts and other feature modules i have.

apollo-clients-module.ts code :

import { NgModule } from "@angular/core";
import { HttpLink } from "apollo-angular-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { Apollo, ApolloModule } from "apollo-angular";
import { ApolloLink } from 'apollo-link';
import { onError } from "apollo-link-error";

@NgModule({
  declarations: [],
  imports: [ApolloModule]
})
export class ApolloClientsModule {

  constructor(private apollo: Apollo, private httpLink: HttpLink) {

    const link = onError(({ graphQLErrors, networkError }) => {
      if(graphQLErrors){
        graphQLErrors.map(({ message, locations, path }) => {
          // Here you may display a message to indicate graphql error
          // You may use 'sweetalert', 'ngx-toastr' or any of your preference
          console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
        })
      }
      if(networkError){
          // Here you may display a message to indicate network error
          console.log(`[Network error]: ${networkError}`);
      }
    });

    apollo.create(
      {
        link : ApolloLink.from([link, httpLink.create({ uri: "/end-point-uri-goes-here/graphql" })]) ,
        cache: new InMemoryCache(),
        defaultOptions : {
          watchQuery : {
            fetchPolicy : 'network-only',
            errorPolicy : 'all'
          }
        }
      },
      "default"
    );  
  }

}

Remember to 'npm install apollo-link-error'

Visit https://www.apollographql.com/docs/angular/features/error-handling/ for more information.

like image 85
don Avatar answered Nov 26 '22 07:11

don


I just got this to work yesterday so no great expert on this but I think it does what you are asking. I couldn't find a good example online either.

This will trigger a dialog over your views with whatever messages you want. I didn't include the dialog code but it lives in my messagesService.

Notice that I left InMemoryCache in there as a note for responses such as this that it isn't needed. It is included in Boost and setup automatically. I was able to read it with readQuery.

I went with Boost and I put it in app.module in the exported class because I couldn't get it to work above in the module providers. Originally I was setup like you did but reaching the messagesService didn't work out. It could also be a service and I may move it there. This is global and you don't have to do anything in your components. Very nice!

app.module.ts

export class AppModule {

// Create and setup the Apollo server with error catching globally.
  constructor(
      private messagesService: MessagesService,
      private apollo: ApolloBoost,
  ) {
    apollo.create({
      uri: 'http://localhost:3000/graphql',
      // cache: new InMemoryCache(),  // This is included by default.  Can be modified.
      onError: ({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.map(({ message, locations, path }) =>
              console.log(
                  `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`),
              console.log('This is a graphQL error!'),
          );
          const msg1 = 'GraphQL error';
          const msg2 = 'Please contact support.';
          this.handleError(msg1, msg2)
        }
        if (networkError) {
          console.log('This is a Network Error!', networkError);
          console.log('Can be called from a query error in the browser code!');
          const msg1 = 'Network error';
          const msg2 = 'Please check your Internet connection.  If OK then contact support .';
          this.handleError(msg1, msg2)
        }
      }
    });
  }


  public handleError(msg1, msg2) {
    this.messagesService.openDialog(msg1, msg2);
  }

}
like image 26
Preston Avatar answered Nov 26 '22 05:11

Preston