全局处理 apollo graphql 错误并在出错时呈现自定义 ErrorHandler 组件

Handling apollo graphql errors globally and render custom ErrorHandler component on error

需要在客户端全局处理 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),
});

请为我的场景建议一种方法。提前致谢

有同样的问题,我们采用的一个解决方案是制作一个 returns 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;