【问题标题】:How to handle error globally in react apollo如何在反应阿波罗中全局处理错误
【发布时间】:2020-01-17 10:45:12
【问题描述】:

我必须在每个请求的 react js 中处理身份验证错误。那么如何全局处理身份验证错误呢?

import {
  ApolloClient,
  ApolloLink,
  InMemoryCache,
  HttpLink
} from "apollo-boost";
import fetch from "isomorphic-unfetch";

let apolloClient = null;

if (!process.browser) {
  global.fetch = fetch;
}

const httpLink = new HttpLink({
  uri: "http://localhost/suitecrm/process.php"
});

const authLink = new ApolloLink((operation, forward) => {
  let token = "";
  if (
    localStorage.getItem("token") != null &&
    localStorage.getItem("token") != ""
  ) {
    token = localStorage.getItem("token");
  }

  operation.setContext({
    headers: {
      "Content-Type": "application/json",
      authorization: token ? `${token}` : ""
    }
  });
  return forward(operation);
});

export default function initApollo(initialState) {
  if (!apolloClient) {
    apolloClient = new ApolloClient({
      link: authLink.concat(httpLink), // Chain it with the HttpLink
      cache: new InMemoryCache()
    });
  }
  return apolloClient;

我正在使用上述文件来调用 graphQL 查询和变异。

谢谢

【问题讨论】:

    标签: reactjs react-apollo


    【解决方案1】:

    您可以使用onErrorapollo-link-error 包来全局获取错误。 Apollo-Boost 也包含此导出。

    import { onError } from 'apollo-link-error';
    
    const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
      if (graphQLErrors)
        graphQLErrors.map(({ message, path }) =>
          console.error(`[GraphQL error]: Message: ${message}, Operation: ${operation.operationName}, Path: ${path}`),
        );
      if (networkError) console.error(`[Network error]: ${networkError}`);
    });
    
    ...
    
    apolloClient = new ApolloClient({
      link: ApolloLink.from([errorLink, authLink, httpLink]),
      cache: new InMemoryCache()
    });
    

    【讨论】:

    • 谢谢,以及如何从后端返回错误。
    • 你需要抛出一个AuthenticationError。检查docs,有一个带有AuthenticationError的例子。
    • 我必须处理来自 PHP 的错误,然后如何从 PHP 向 apollo 客户端返回错误消息。
    猜你喜欢
    • 2019-07-06
    • 2020-03-18
    • 2019-04-19
    • 2017-11-20
    • 2021-02-02
    • 1970-01-01
    • 2021-07-13
    • 2019-02-19
    • 2021-09-17
    相关资源
    最近更新 更多