Apollo Client(React):处理意外错误

问题描述 投票:17回答:2

我一直在审查Apollo文档,但我没有看到如何在Apollo客户端中处理服务器错误的信息。

例如,假设服务器要么:

  • 超时
  • 变得无法到达
  • 出乎意料地失败了

如何在客户端处理? Apollo目前失败,出现以下错误:

未处理(在react-apollo中)错误:GraphQL错误:不能......

我想避免这种情况发生并处理这些错误。我怎么能用React Apollo这样做?


以供参考:

我目前正在使用React-Apollo和Redux。

javascript reactjs apollo react-apollo apollo-client
2个回答
6
投票

错误在组件道具的error字段中传递:http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error

function MyComponent({ data }) {
  if (data.error) {
    return <div>Error!</div>;
  } else {
    // ...
  }
}

export default graphql(gql`query { ... }`)(MyComponent);

如果我们检测到存在错误并且组件中未访问error字段,则会打印该消息。

您可以编写一个更高阶的组件来以通用方式处理错误,这样您就可以用它包装所有组件。


0
投票

服务器错误可能意味着没有来自服务器的数据对象,因此也没有可用的错误消息。

假设您查询一些用户数据,以便结果对象为data.user。然后你要测试:

if (data.loading !== true && data.user === undefined) {
   /* handle the error here */
}

如果您不想看到错误消息,可以向查询添加选项:

graphql(query, {
  options: {
    errorPolicy: 'ignore'
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.