【问题标题】:Handling apollo graphql errors globally and render custom ErrorHandler component on error全局处理 apollo graphql 错误并在错误时呈现自定义 ErrorHandler 组件
【发布时间】:2018-08-07 07:57:02
【问题描述】:

需要在客户端全局处理 Apollo graphql 错误,并在错误时渲染自定义 ErrorHandler 组件。所以我使用了 Apollo 的 afterwareapollo-link-error

import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error'


const httpLink = new HttpLink({ uri: '/graphql' });

const logoutLink = onError(({ networkError }) => {
  if (networkError.statusCode === 401) {
    //need to dispatch a redux action so that ErrorHandler component renders
  }
})

const client = new ApolloClient({
  link: logoutLink.concat(httpLink),
});

我的解决方案(我猜这不是正确的方法)

import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { render } from 'react-dom';

import ErrorHandler from '../utils/ErrorHandler';

const httpLink = new HttpLink({ uri: '/graphql' });

const logoutLink = onError(({ networkError }) => {
  if (networkError.statusCode === 401) {
    const targetDiv = document.getElementById('serviceErrorHandler');       
    render(
       <ErrorHandler message={networkError.message}/>,
       targetDiv
    );
  }
})

const client = new ApolloClient({
  link: logoutLink.concat(httpLink),
});

请为我的方案提出一种方法。提前致谢

【问题讨论】:

    标签: react-redux apollo react-apollo apollo-client


    【解决方案1】:

    遇到同样的问题,我们采用的一种解决方案是创建一个返回 onError 并采用参数(存储)的函数:

    const errorHandler = store => onError((errors) => {
      if (errors.networkError) {
        store.dispatch(createApolloErrorAction({
          message: GENERIC_ERROR_FETCHING_STRING,
        }));
      }
    });
    

    并在一个包装函数中使用它来传入存储:

    let apolloClient = null;
    
    export const createApolloClient = (reduxStore) => {
      const cache = new InMemoryCache();
      const link = errorHandler(reduxStore).concat(otherLink);
    
      apolloClient = new ApolloClient({ link });
    
      return apolloClient;
    };
    export const getApolloClient = () => apolloClient;
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2018-12-18
      • 2017-06-23
      • 1970-01-01
      • 2020-12-21
      • 2018-07-24
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      相关资源
      最近更新 更多