I'm using GraphQL and mongoose on the server.
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"
}]
}
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) });
});
How can this be done?
The previous answer from @stubailo does not seem to cover all use cases. If I throw an error on my server side code the response code will be different than 200 and the error will be handled using
.catch()
and not using.then()
.Link to the issue on GitHub.
The best is probably to handle the error on both
.then()
and.catch()
.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 errors from the mutation currently show up in the
errors
field on the response insidethen
. I think there's definitely a claim to be made that they should show up in thecatch
instead, but here's a snippet of a mutation from GitHunt:Using graphql tag notation, yo have access to errors:
https://www.apollographql.com/docs/react/essentials/mutations.html