'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:

Console Results

Error Displayed in Browser:

Error Modal



Solution 1:[1]

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.

You can find additional information and examples of this approach here: enter link description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GeorgeButter