Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent 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 Output:

https://i.stack.imgur.com/8NaKc.png

Error Message in Browser:

https://i.stack.imgur.com/Kg7Yt.png

Answer №1

The issue stems from the client, not the mutation itself, so your try-catch block won't be able to catch it. To address this, you can implement error handling on the client side. Here's an example of how to do that:

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

Since you encountered an authorization error, I recommend checking your headers.

For more detailed information and examples using this approach, please refer to: enter link description here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

Controlling the access to simpleJWT tokens in Django-React authentication to restrict user permissions

My backend has two React frontends: one for general users and the other specifically for admin users with the is_staff attribute. I have customized TokenObtainPairSerializer to add extra fields like 'is_staff'. Now, I'm considering how to r ...

When working in React, I encountered a problem with the for of loop, as it returned an error stating "x is undefined." Although I could easily switch to using a simple for loop, I find the for of loop to

I'm encountering an issue when using a for of loop in React, as it gives me an error stating that "x is undefined". import { useEffect } from "react"; export default function HomeContent() { useEffect(() => { let content = document ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Having trouble printing webpages? Need a useful tutorial on how to print web pages created using jQuery UI, jqGrid, and Zend?

I have been tasked with printing web pages of a website that utilize jqgrid, Jquery calendar, various Jquery UI components, and background images. The server side is built with Zend Framework. Although I lack experience in web page printing, this has beco ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

Choose from a variety of options using Select and Checkbox components, but limit your choices to a maximum selection

Looking to implement the Select and Checkbox components from MUI with the ability for users to select multiple options. I want to limit their selection to a maximum of 3 choices, but I can't seem to find the props to set this restriction. Is there a w ...

Issue encountered when sending information to asmx web service via ajax and displaying the result on an HTML page with a javascript function

I have developed an ASMX web service that looks like this: [ScriptService] public class CurrencyData : System.Web.Services.WebService { [WebMethod] public string DisplayCurrency(double amount, string sign ,string style) { swi ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

Alias destructuring for arrays within nested objects

I'm currently attempting to change the names of certain objects from one array (eventFetch) and transfer them into another array (mapEvents). I initially tried using destructuring aliases for this task, but since I need to rename a nested object, it d ...

Nexus and GraphQL: The root typing path for the "context" type is not found

I’m currently working on integrating GraphQL into Next.js API routes. For writing the GraphQL schema, I’m utilizing Nexus. Here are the two essential files: context.ts and schema.ts, that help in setting up Nexus development mode. // context.ts import ...

What is the best way to set the Material UI Mini Variant Drawer to automatically open on larger screens?

I need assistance in modifying the Material UI Mini Variant Drawer code so that the full-sized drawer is initially open on large and extra-large screen sizes, rather than closed. The mini drawer should only appear when the screen size is medium or smaller. ...

Tips on when to display the "Email Confirmation" input text box only after updating the old email

Oh no!! Yes, that's exactly what I desire! I've been facing obstacles in trying to understand how to display the "Email Confirm" input text-box ONLY when the old email has been updated. Can someone point out where I might have gone wrong? :( ...

Displaying object properties in React and rendering them on the user interface

Within my React application, I am retrieving data from an API using the following code snippet: function PlayerPage() { interface PlayerDataType { id: number; handle: string; role: string; avatar: string; specialAbilities: null; s ...