Dealing with errors in Smart Query using Nuxt and Vue Apollo: How to navigate to specific error pages for 404, 400, or 500 errors and is it possible to catch

When utilizing Smart Query for redirection, how can we redirect to a 400 page?

While working with Vue Apollo, I attempted the following:

    apollo: {
        queryName: {
            prefetch: true,
            query: wrongQuery,
    
            error(errorData) {
                this.$nuxt.error({
                    statusCode: 500,
                    message: 'Error message',
                });
            },
        },
    };

Unfortunately, if the page is reloaded, the redirection does not function properly due to server-side rendering:

https://i.sstatic.net/H4zhU.png

Even when attempting a global error handler like the one below:

    // /plugins/apollo-error-handler.js
    export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
        console.log(networkError)
        nuxtContext.error({
          statusCode: 404,
          message: 'Error message',
        });
    };

Only error logging seems to be functional, as redirection remains ineffective.

Is there any method to handle errors within smart queries and redirect to a 400 page, for example?

Can we implement error handling in smart queries similar to try...catch... in asyncData() to prevent application crashes?

Answer №1

This helpful solution can be found here!

function redirectOnError({ redirect }) {
  const errorLink = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message }) => {
        if (`${message}` === 'Unauthenticated.') {
          redirect('/login');
          localStorage.setItem('logged', false);
        }
      });
    }
    if (networkError) {
      console.log(`[Network error]: ${networkError}`);
    }
  });
  
  return {
    defaultHttpLink: false,
    link: ApolloLink.from([errorLink, createHttpLink({
      credentials: 'include',
      uri: 'http://localhost:8000/graphql',
      fetch: (uri, options) => {
        options.headers['X-XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN');
        return fetch(uri, options);
      }
    })]),
    cache: new InMemoryCache()
  };
}

I hope this solution proves useful for you!
Best regards!

Answer №2

This type of smart query has its limitations, so I prefer to manage it within my Vuex store. While I'm not certain if this is the best practice, it's working well for me at the moment.

async performVuexAction({ dispatch }, { input }) {
  try {
    const { errors, data } = await this.app.apolloProvider.defaultClient.mutate({
      mutation: yourGraphqlMutationHere,
      errorPolicy: 'all',
      variables: {
        input: fancyInput,
      },
    })

    if (errors) {
      return dispatch('handleErrors', 'we encountered some issues')
    }

    dispatch('anotherActionToHandleData', data.Address.createForCompany)
    
    console.log('Success!')
  } catch (error) {
    // Here, you can catch and handle any errors that occur
    dispatch('handleErrors', 'the call was unsuccessful')
  }
},

Alternatively, utilizing the onError callback is also a good option if you're comfortable configuring it: https://www.apollographql.com/docs/react/data/error-handling/

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

Why am I not receiving any results from the communication between JavaScript and PHP using an HTTP GET request?

Currently, I have a small JavaScript program running within an HTML5 canvas and included a HTTP GET request function in my JavaScript code. The function itself is functioning properly as I tested it with multiple examples from the internet, all of which wo ...

Node.js and react-create-app are not compatible with each other

I am currently using node.js version 14.6.0 and node-v version 7.20.0 To replicate the issue, follow these steps: npx create-react-app my-app2 Once everything is installed, run npm i After completing the above steps, you may encounter the following warn ...

Utilizing jQuery to send multiple values via an ajax request

I am looking to modify this script to send multiple values using AJAX instead of just a single value. files.php $(".search_button").click(function() { var search_word = $("#search_box").val(); var dataString = 'search_word='+ search_word ...

After making changes to Vue, jQuery's data is now obsolete

Currently, I am in the process of transitioning from Jquery to Vue.js 3. As a result of this migration, Vue updates the DOM while Jquery still contains outdated information. My question is: How can I make Jquery reflect the new data just like Vue and Jav ...

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

Dynamically load the configuration for a JQuery plugin

Currently, I am utilizing a JQuery plugin from this source. My goal is to dynamically load the configuration of the plugin without directly modifying it within the plugin file. Below are the default options provided by the plugin: $.Slitslider.def ...

What is the best way to pass compile-time only global variables to my code?

I am looking for a way to easily check if my code is running in development mode, and based on that information, do things like passing the Redux DevTools Enhancer to the Redux store. I know I can use process.env.NODE_ENV for this purpose, but I find it ...

Reveal and conceal using CSS animations

I am working on adding animation effects to show and hide HTML elements triggered by a button click. The button toggles a "hide" class to display or hide the element. Check out my code snippet: const toggleButton = document.querySelector('button ...

"Troubleshooting a bug: GetElementById function fails to find elements with hyphenated

When calling attr('id') on an immutable id attribute for an HTML element, my code runs smoothly when the id contains no hyphens. However, it encounters issues when the id includes a hyphen. $('.coloursContainer .radio-box').live(' ...

What is the best way to activate a JavaScript function once a page has finished loading?

Hey there! I have a webpage with 2 text input fields and a DIV element. The first input field is for user input, while the second one is readonly. When the user hits Enter in the first input field, a new page loads into the DIV based on the query result f ...

What is the best way to incorporate items into Redux reducers?

Incorporating Redux with Next JS, I am faced with the challenge of adding an array of objects to it. Within my application, there exists a form containing multiple inputs, and in order to accommodate these inputs, I have structured a form consisting of 10 ...

Steps for creating an AJAX request to a variable defined within the local scope

I want to create a list using a JSON object that I already have stored in a variable. I have been exploring the dynatable library and its documentation on populating a table using AJAX to receive JSON data. However, I am stuck on how to make it work with ...

unable to toggle the navbar

Currently, I am facing an issue with the navbar-toggle button while using Bootstrap. Initially, I thought the problem was with my navbar code, so I tried pasting the example from the Bootstrap Website, but it did not work either. The button appears, but t ...

jQuery Waypoints Error: The sticky functionality is missing and cannot be utilized in this context

Trying to anchor an element at the top of a WordPress page using the jQuery Waypoints plugin. <script src="path/to/waypoints.min.js"></script> <script> $('#myelement').waypoint('sticky'); </script> However, t ...

The presence of an undefined variable in `esm.js` is resulting in an overwhelming amount of

After upgrading from Node v14 to Node v16, I encountered a strange error specifically when running node with node -r esm. The error message reads: ReferenceError: myVar is not defined This results in an extensive output of the esm.js module spanning 5000 ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

Converting a JS string into HTML markup

I recently developed a basic web application to manage telnet connections with routers using Node.js, Express, and WebSockets. After establishing a connection, the terminal stream is transmitted through a websocket as UTF-8 strings. However, my current is ...

How to retrieve the chosen option from a drop-down menu in WebDriver using JavaScript without relying on the Select Class

Currently, I am in the process of utilizing Webdriver with Java. My goal is to retrieve the selected value from a combobox without relying on the Select class provided by Webdriver. The specific markup that I am dealing with is as follows: <select nam ...

Guide to implementing client-side validation in MVC 4 without relying on the model

Currently, I am developing an ASP.NET MVC 4 project where I have decided not to utilize View Models. Instead, I am opting to work with the classes generated from the Entities for my Models. I am curious if there are alternative methods to achieve this. A ...

Every time I refresh the page, the user is automatically logged out

I am currently working on developing an admin dashboard using nextjs 13. I have encountered a specific issue where the user is redirected to the login page every time they reload the page. Upon inspecting in developer mode, I noticed that cookies are still ...