【问题标题】:how to access apollo client error object properties如何访问 apollo 客户端错误对象属性
【发布时间】:2021-10-14 09:09:30
【问题描述】:

我正在向 GraphQL 服务器获取查询,如果出现问题,该服务器会抛出错误。现在,我想访问该错误,但 Apollo Client 向我显示了一般的Error: Network error: Response not successful: Received status code 500。 通过将 onError 属性添加到我的查询中,我可以在控制台中看到 Error 对象,但前提是它包含在 {} 中,否则它只是文本。

这是我的代码:

  const { data, loadMore, loading, error, retry } = useRetryableQuery<
    GetDevices,
    DevicesQueryVariables
  >(devicesQueries.GetDevices, {
    onError: (networkError) => {
      console.log(networkError); //this will show me the error as a whole text and not an object
      console.log({ networkError }) // this will show me an object which its properties I cannot access
    },
    errorPolicy: "all",
    notifyOnNetworkStatusChange: true,
    paginationPath: ["paging"],
    itemsPaths: [["filteredDevices", "rows"]],
    variables: {
      ...queryVariables,
      connectionPaging: {
        offset: 0,
        limit: PAGE_SIZE,
      },
    },
  });

如何访问嵌套在 networkError 对象中的属性?

第一个屏幕截图没有 {} 第二个是 {}

提前致谢!

【问题讨论】:

    标签: javascript apollo-client


    【解决方案1】:

    该问题与此 Apollo 客户端问题有关:useQuery() refetch throws on error instead of flowing through hook,因此直接从 ApolloProvider 获取错误允许我访问从后端发送的错误:

    const errorLink = useMemo(
    () =>
      onError((error) => {
        const message = getApolloError({ graphQLErrors: error.graphQLErrors 
     });
        if (message) {
          localStorage.setItem("error", message);
        } else {
          localStorage.removeItem("error");
        }
        if (message === "Session expired.") {
          logout(true);
        }
      }),
     [logout]
    );
    
    const client = useMemo(
     () =>
       new ApolloClient({
         cache,
         link: ApolloLink.from([errorLink, authLink, httpLink]),
         defaultOptions: {
           watchQuery: {
             fetchPolicy: "network-only",
           },
           query: {
             fetchPolicy: "network-only",
           },
         },
       }),
     [httpLink, errorLink]
    );
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2022-08-02
      • 2019-01-10
      相关资源
      最近更新 更多