Apollo GraphQL 客户端 + Next.JS 错误处理

Apollo GraphQL Client + Next.JS Error Handling

该组件很好地呈现了错误状态,但异常在控制台中显示为未捕获,并且在浏览器的 next dev 中显示了一个对话框。有没有办法处理预期的错误来抑制这种行为?

import { useMutation, gql } from "@apollo/client";
import { useEffect } from "react";

const CONSUME_MAGIC_LINK = gql`
  mutation ConsumeMagicLink($token: String!) {
    consumeMagicLink(token: $token) {
      token
      member {
        id
      }
    }
  }
`;

export default function ConsumeMagicLink({ token }) {
  const [consumeMagicLink, { data, loading, error }] =
    useMutation(CONSUME_MAGIC_LINK);

  console.log("DATA", data, "loading:", loading, "error:", error);

  useEffect(() => {
    try {
      consumeMagicLink({ variables: { token } });
    } catch (e) {
      console.log(e);
    }
  }, []);

  var text = "Link has expired or has been used previously";

  if (data) text = "SUCCESS: REDIRECTING";
  if (loading) text = "Processing";
  if (error) text = "Link has expired or has been used previously";

  return (
    <div>
      <h2>{text}</h2>
    </div>
  );
}

控制台结果:

浏览器中显示错误:

错误来自客户端而不是突变,因此您的 try-catch 无法捕捉到它。要处理此问题,您可以将错误处理添加到客户端,例如:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.forEach(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = new HttpLink({
  uri: "some invalid link"
});

const client = new ApolloClient({
  link:from([httpLink,errorLink]),
  cache: new InMemoryCache()
})

由于您遇到授权错误,我建议您检查您的 headers。

您可以在此处找到有关此方法的更多信息和示例: enter link description here