Apollo客户端突变错误处理

Loc*_*0_0 8 apollo graphql apollo-client

我在服务器上使用GraphQL和猫鼬。

发生验证错误时,GraphQL突变会发送状态码为200的响应。在客户端,响应如下所示:

{
  "data": null,
  "errors": [{
    "message": "error for id...",
    "path": "_id"
  }]
}
Run Code Online (Sandbox Code Playgroud)

我想使用catchapollo-client突变承诺的功能来访问验证错误。就像是:

      this.props.deleteProduct(this.state.selectedProductId).then(response => {
         // handle successful mutation
      }).catch(response => {
         const errors = response.errors; // does not work
         this.setState({ errorMessages: errors.map(error => error.message) });
      });
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

tgd*_*gdn 6

@stubailo 的先前答案似乎并未涵盖所有用例。如果我在服务器端代码上抛出错误,响应代码将与 200 不同,并且将使用.catch()和不使用.then().

链接到 GitHub 上的问题。

最好的可能是处理双方的错误.then().catch()

const { deleteProduct } = this.props;
const { selectedProductId } = this.state;

deleteProduct(selectedProductId)
  .then(res => {
      if (!res.errors) {
          // handle success
      } else {
          // handle errors with status code 200
      }
  })
  .catch(e => {
      // GraphQL errors can be extracted here
      if (e.graphQLErrors) {
          // reduce to get message
          _.reduce(
             e.graphQLErrors,
             (res, err) => [...res, error.message],
             []
          );
      }
   })
Run Code Online (Sandbox Code Playgroud)

  • 想知道为什么没有更优雅的方法来提取错误消息和错误代码。 (6认同)

stu*_*ilo 2

注意:这个答案(可以说是整个问题)现在已经过时了,因为突变错误出现在catch最新版本的 Apollo 客户端中。

目前,来自突变的 GraphQL 错误显示在errors内部响应的字段中then。我认为肯定有人声称它们应该出现在替代中,但这里有来自GitHuntcatch的突变片段:

// The container
const withData = graphql(SUBMIT_REPOSITORY_MUTATION, {
  props: ({ mutate }) => ({
    submit: repoFullName => mutate({
      variables: { repoFullName },
    }),
  }),
});

// Where it's called
return submit(repoFullName).then((res) => {
  if (!res.errors) {
    browserHistory.push('/feed/new');
  } else {
    this.setState({ errors: res.errors });
  }
});
Run Code Online (Sandbox Code Playgroud)