graphql - 如何处理 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)
}
},
},
我得到的网络响应 -
解决方案
使用 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
从服务器记录您的日志。
推荐阅读
- node.js - 每个项目的猫鼬查找ID?
- python-3.x - python字典子字符串键
- python-3.x - pyodbc [DBNETLIB]ConnectionOpen (Invalid Instance()) 错误
- c# - 有人可以解释为什么这个 LINQ-to-entitiy 查询会导致错误,以及为什么我的解决方案会修复它吗?
- javascript - React-router/history 阻止“beforeinstallprompt”事件触发
- javascript - 使用 console.log 创建带有明确标题/文本的链接
- javascript - 创建一个不基于数据库的 Like 计数器
- google-ads-api - Google Ads 和 Facebook Ads 的替代品
- android-camerax - CameraX 在获取 cameraProviderFuture 时崩溃
- react-native - 类型突变上不存在字段“登录”