Nuxt and Vue Apollo. How to handle errors inside Smart Query with redirection to 404/400/500 error page? Can we catch such errors?

With regular HTTP request, we may create redirection with asyncData({error}){…}

What should we use for redirecting to 400 page using Smart Query?

With Vue Apollo, I am trying to use

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

In case if we reload the page, redirection doesn’t work. We still got an error becouse server side rendering:

enter image description here

With global error handler like:

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

Only errors logging works. Redirection doesn’t work at all.

Do we have any way to handle errors inside smart queries with redirection to 400 page for example?

Can we catch such errors in smart query? Like try…catch… in asyncData() to prevent app crash.

10 thoughts on “Nuxt and Vue Apollo. How to handle errors inside Smart Query with redirection to 404/400/500 error page? Can we catch such errors?”

  1. The smart query like this is pretty limited and so, I prefer to handle it in my Vuex store. Not sure if it’s the best practice but it works great for me right now.

    async niceFancyVuexAction({ dispatch }, { fancyInput }) {
      try {
        const { errors, data } = await this.app.apolloProvider.defaultClient.mutate({
          mutation: yourGraphqlMutationHere,
          errorPolicy: 'all',
          variables: {
            input: fancyInput,
          },
        })
    
        if (errors) {
          return dispatch('handleErrors', 'we got some errors')
        }
    
        dispatch('anotherNiceFancyVuexAction', data.Address.createForCompany)
        
        console.log('success !')
      } catch (error) {
        // here, you could catch the error and maybe make a redirect
        dispatch('handleErrors', 'the call was not successfull')
      }
    },
    

    Otherwise, yeah using the onError link is also a good idea if you feel configuring it: https://www.apollographql.com/docs/react/data/error-handling/

    Reply

Leave a Comment