【问题标题】:How to use import { onError } from 'apollo-link-error' in angular to handle all errors如何在 Angular 中使用 import { onError } from 'apollo-link-error' 来处理所有错误
【发布时间】:2019-12-22 18:36:06
【问题描述】:

以下是我的 apollo angular 设置代码:

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

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

我想在下面使用:

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}`);
});

如何链接它,以便能够在控制台中获取错误?

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow!您的控制台中是否有任何错误?您当前应用程序的实际行为是什么,即为什么它目前不工作?
  • 我想使用 OnError 来处理错误,但没有得到使用它的详细示例。
  • 我认为它会在失败时崩溃,您会在浏览器的控制台中看到它们。
  • @technogeek1995 是的,但是我想在我的网站页面上显示 graphql 错误
  • 我不知道怎么做,但我会编辑您的问题,以明确您要完成的工作

标签: angular graphql apollo-angular


【解决方案1】:

以下是我如何使用 'apollo-link-error' 来处理 graphQL 错误和网络错误。我创建了一个名为 apollo-clients-module.ts 的单独模块,并将其导入到 app.module.ts 和我拥有的其他功能模块中。

apollo-clients-module.ts 代码:

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"
    );  
  }

}

记得'npm install apollo-link-error'

访问https://www.apollographql.com/docs/angular/features/error-handling/了解更多信息。

【讨论】:

    【解决方案2】:

    我昨天才开始工作,所以在这方面没有什么伟大的专家,但我认为它可以满足您的要求。我在网上也找不到很好的例子。

    这将触发一个关于您的视图的对话框,其中包含您想要的任何消息。我没有包含对话代码,但它存在于我的 messagesService 中。

    请注意,我将 InMemoryCache 留在那里作为对诸如此类不需要它的响应的注释。它包含在 Boost 中并自动设置。我可以使用 readQuery 读取它。

    我选择了 Boost,并将它放在导出类的 app.module 中,因为我无法让它在模块提供程序中运行。最初我像你一样设置,但到达 messagesService 没有成功。它也可以是一项服务,我可以将它移到那里。这是全球性的,您无需在组件中执行任何操作。很不错!

    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);
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2019-12-05
      • 2020-04-08
      • 2020-07-26
      • 1970-01-01
      • 2020-03-01
      • 2018-08-31
      • 1970-01-01
      • 2018-01-28
      相关资源
      最近更新 更多