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

时间:2018-02-27 15:43:50

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

需要在客户端全局处理Apollo graphql错误,并在出错时呈现自定义 ErrorHandler 组件。所以我使用了Apollo的 afterware apollo-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),
});

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

1 个答案:

答案 0 :(得分: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;