Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Apollo Graphql query error in Vue.JS?

I am using Vue.js with Vue-Apollo and trying to fetch shared member list using query. I am using the graphQL service in backend.

I am using apollo 'error' function to handle GraphQL error. When the request is made with invalid input, I can see the errors in the network tab, I can see the JSON for the custom errors messages. But I can't console the errors in 'error' function.

Here is the apollo query that is used to fetch shared member list -

apollo: {
    sharedMembers: {
      query: gql`
        query item($uuid: ID) {
          item(uuid: $uuid) {
            ...itemTemplate
            members {
              ...member
              permission
            }
          }
        }
        ${ITEM_TEMPLATE}
        ${MEMBER}
      `,
      variables() {
        return {
          uuid: this.$route.params.uuid,
        }
      },
      update(data) {
        return data.item.members
      },
      error(error) {
       console.log('errors', error)
      }
    },
  },

The network response I got -

network_error

like image 629
khushbu patel Avatar asked Jul 07 '19 18:07

khushbu patel


1 Answers

Using graphQLErrors

You could get the errors by looking in the error object for graphQLErrors:

error(error) {
  console.log('errors', error.graphQLErrors)
}

or

error({ graphQlErrors }) {
  console.log('errors', graphQLErrors)
}

Using apollo-error-link

You can use apollo-error-link to help solve your problem if the above doesn't work, docs here.

Here's an example from the docs and I added to it in the networkErrors section to show what you can do to edit the error message you see in your error block, or catch block if its a mutation.

import { onError } from "apollo-link-error";

const link = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

  if (networkError) {
    // Add something like this to set the error message to the one from the server response
    networkError.message = networkError.result.errors[0].debugMessage

    console.log(`[Network error]: ${networkError}`)
  };
});

And then in your code:

error(error) {
  console.log('error-message', error.message)
}

The console should then log your debugMessage from the server.

like image 162
David North Avatar answered Sep 19 '22 16:09

David North