Apollo client mutation error handling

I am using GraphQL and mongoose on the server.

When a validation error occurs, the GraphQL mutation sends a response with a status code of 200. On the client side, the response looks like this:

{
  "data": null,
  "errors": [{
    "message": "error for id...",
    "path": "_id"
  }]
}
      

Run codeHide result


I would like to access the validation error using the catch

apollo-client mutation promise functionality . 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) });
      });
      

Run codeHide result


How can I do that?

+3


source to share


2 answers


Note. This answer (and possibly the whole question) is outdated as mutation errors show up catch

in later versions of Apollo Client.

GraphQL errors from mutation are currently showing up in a field errors

in the response inside then

. I think there is a definite claim that they should appear in catch

instead, but here's a snippet of the mutation from GitHunt :



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

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

      

+2


source


The previous answer from @stubailo doesn't seem to cover all use cases. If I abandon the server side code the response code is different from 200 and the error is handled with .catch()

and won't use .then()

.

Link to question on GitHub.



Best of all, perhaps, to cope with an error as .then()

well as on .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],
             []
          );
      }
   })

      

+3


source







All Articles