khushbu patel
khushbu patel

Reputation: 105

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

Upvotes: 7

Views: 9460

Answers (2)

Y. Russanov
Y. Russanov

Reputation: 11

unfortunately i couldn't find out how i'd handle errors in such of graphql method call, but as an option you could provide onError method to ApolloClient constructor options. first argument is the error object. hopefully it may help. like so..

const apolloClient = new ApolloClient({
  uri: 'http://localhost:4000',
  onError(err) {
    console.log(err)
  },
})

Upvotes: -1

David North
David North

Reputation: 447

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.

Upvotes: 7

Related Questions