如何使用 apollo 客户端在 graphql 的角度处理错误?

Posted

技术标签:

【中文标题】如何使用 apollo 客户端在 graphql 的角度处理错误?【英文标题】:How to handle error using apollo client in angular for graphql? 【发布时间】:2020-11-24 12:55:52 【问题描述】:

下面是我的代码。我一直试图以某种方式将错误变量链接到 GraphQL Module 。请提供一种方法来实现这一点。

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 

我需要有关与 GraphQL Module 链接错误的帮助。我怎样才能做到这一点?提前致谢。

【问题讨论】:

【参考方案1】:

Apollo 链接是可组合的单元。每个链接都是一个函数,它将操作作为参数并返回一个 observable。 Apollo 链接就像一个中间件一样可以转换请求及其结果。

您可以将错误链接组合到主模块为

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

【讨论】:

以上是关于如何使用 apollo 客户端在 graphql 的角度处理错误?的主要内容,如果未能解决你的问题,请参考以下文章