阿波罗客户端突变错误处理
问题描述:
我在服务器上使用GraphQL和猫鼬。阿波罗客户端突变错误处理
当验证错误发生GraphQL突变发送带有状态代码200的响应在客户端的响应看起来是这样的:
{
"data": null,
"errors": [{
"message": "error for id...",
"path": "_id"
}]
}
我想获得访问验证错误使用apollo-client突变许诺的catch
功能。喜欢的东西:
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) });
});
如何才能做到这一点?
答
注意:这个答案(可以说是整个问题)现在已经过时了,因为在更新版本的Apollo客户端中,catch
中会出现突变错误。
来自突变的GraphQL错误目前显示在then
内的响应中的errors
字段中。我认为有一定要进行,他们应该在catch
显示,而不是要求,但这里有一个突变从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 });
}
});
答
似乎从@stubailo以前的答案并不涵盖所有用例。如果我在服务器端代码上发生错误,则响应代码将不同于200,并且将使用.catch()
而不是使用.then()
来处理错误。
Link到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],
[]
);
}
})
+1
不知道为什么没有更优雅的方式来提取错误消息和错误代码。 – Theson
尝试使用'throw'语句创建'Error'实例 –