首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在react apollo中全局处理错误

如何在react apollo中全局处理错误
EN

Stack Overflow用户
提问于 2019-08-17 20:37:17
回答 1查看 1.2K关注 0票数 2

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

代码语言:javascript
运行
复制
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;

我正在使用上面的文件进行call graphQL查询和突变。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2019-08-18 00:22:20

您可以使用apollo-link-error包的onError全局获取错误。Apollo-Boost也包括这个出口。

代码语言:javascript
运行
复制
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()
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57536338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档