简体   繁体   中英

Apollo GraphQL Client + Next.JS Error Handling

The component renders the error state just fine, but the exception is displayed as uncaught in the console and a dialogue is displayed in next dev on the browser. Is there a way to handle expected errors to squelch this behavior?

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>
  );
}

Console Results:

控制台结果

Error Displayed in Browser:

错误模式

The error is from the client instead of the mutation so your try-catch cannot catch it. To handle this you can add the error handling to the client, for example:

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()
})

And as you got authorization error, I suggest you check your headers.

With nextjs, how to prevent modal show up every occur error in Apollo Link? Anyone help me?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM