首页 > 解决方案 > 如何处理 Vue.JS 中的 Apollo Graphql 查询错误?

问题描述

我正在将 Vue.js 与 Vue-Apollo 一起使用,并尝试使用查询来获取共享成员列表。我在后端使用 graphQL 服务。

我正在使用 apollo 'error' 函数来处理 GraphQL 错误。当使用无效输入发出请求时,我可以在网络选项卡中看到错误,我可以看到自定义错误消息的 JSON。但我无法解决“错误”功能中的错误。

这是用于获取共享成员列表的阿波罗查询 -

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

我得到的网络响应 -

网络错误

标签: graphqlvue-apollo

解决方案


使用 graphQLErrors

您可以通过查看 graphQLErrors 的错误对象来获取错误:

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

或者

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

使用 apollo-error-link

如果上述方法不起作用,您可以使用 apollo-error-link 来帮助解决您的问题,此处的文档

这是文档中的一个示例,我在 networkErrors 部分中添加了它,以显示您可以做什么来编辑您在错误块中看到的错误消息,或者如果它是突变则捕获块。

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}`)
  };
});

然后在您的代码中:

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

然后控制台应该debugMessage从服务器记录您的日志。


推荐阅读