如何在进行 graphql 查询时捕获 Apollo Consumer 中的错误

How to capture Errors in Apollo Consumer when making graphql queries

这就是我查询 Graphql 引擎的方式。

export GraphQLWrapper <TData, TParam = {}>({
  query,
  extractData,
  children,
  queryVariables,
  skip,
}: AsyncWrapperProps<TData, TParam>) => {
  return (
    <ApolloConsumer>
      {client => {
        const loadOptions = (
          searchString: string,
        ): Promise<SelectOptionType[]> =>
          skip
            ? Promise.resolve([])
            : client
                .query<
                  TData,
                  | AsyncSelectSearchVariables
                  | (AsyncSelectSearchVariables & TParam)
                >({
                  query,
                  variables: {
                    search: `${searchString || ""}%`,
                    ...queryVariables,
                  },
                })
                .then(extractData);
        return <div>{children(loadOptions)}</div>;
      }}
    </ApolloConsumer>
  );
};

我有以下用于 运行 Graphql 查询的代码。我如何使用它来捕获 GraphQL 错误。谢谢你。

这就是我访问上述组件的方式:

const extractData = ({ data }: ApolloQueryResult<AccountData>) =>
  data && data.vitm_account ? data.vitm_account : [];

  return (
    <GraphQLWrapper query={ACCOUNT_NAME_QUERY} extractData={extractData}>
      {accountSelect}
    </GraphQLWrapper>
  );
const setError = useContext(ErrorContext);

  const handleError = (error: ApolloError) => {
    setError(error);
    return [];
  };

  return (
    <ApolloConsumer>
      {client => {
        const loadOptions = (
          searchString: string,
        ): Promise<SelectOptionType[]> =>
          skip
            ? Promise.resolve([])
            : client
                .query<
                  TData,
                  | AsyncSelectSearchVariables
                  | (AsyncSelectSearchVariables & TParam)
                >({
                  query,
                  variables: {
                    search: `${searchString || ""}%`,
                    ...queryVariables,
                  },
                })
                .then(extractData)
                .catch(handleError);
        return <div>{children(loadOptions)}</div>;
      }}
    </ApolloConsumer>
  );
};

我们可以使用 catch 将错误消息发送到使用 .catch 函数的 handleError 方法。