问题描述
我在服务器上使用 GraphQL 和 mongoose.
I'm using GraphQL and mongoose on the server.
当发生验证错误时,GraphQL 突变会发送一个状态码为 200 的响应.在客户端,响应如下所示:
When a validation error occurs the GraphQL mutation sends a response with status code 200. On the client side the response looks like this:
{
"data": null,
"errors": [{
"message": "error for id...",
"path": "_id"
}]
}
我想使用 apollo-client 突变承诺的 catch
功能访问验证错误.类似的东西:
I would like to get access to the validation error using the catch
functionality of the apollo-client mutation promise. Something like:
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) });
});
如何做到这一点?
推荐答案
注意:这个答案(可以说是整个问题)现在已经过时了,因为在更新的版本中 catch
中出现了突变错误Apollo 客户端.
Note: This answer (and arguably the whole question) is now outdated, since mutation errors show up in catch
in more recent versions of Apollo Client.
来自突变的 GraphQL 错误当前显示在 then
内响应的 errors
字段中.我认为肯定有人声称它们应该出现在 catch
中,但这里有一个来自 GitHunt:
GraphQL errors from the mutation currently show up in the errors
field on the response inside then
. I think there's definitely a claim to be made that they should show up in the catch
instead, but here's a snippet of a mutation from GitHunt:
// 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 });
}
});
这篇关于Apollo 客户端变异错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!