5

I want to show some errors that comes from graphql server to user.

Have some component with callback that use some mutation

onSave() => {
    this.props.mutate({
        mutation: CHANGE_ORDER_MUTATION,
        variables: {
            ids,
        },
    }).catch((e) => {
        console.log(e.graphQLErrors) <--- e.graphQLErrors is always empty array = []
    })
}

While I'm able to see the graphQLErrors error with apollo-link-error link.

const errorLink = onError(({ graphQLErrors, networkError }) => { console.log(graphQLErrors) <--- errors from server });

comalex3
  • 2,497
  • 4
  • 26
  • 47

2 Answers2

7

Migration to apollo-server instead of express-graphql solve the problem.

Or you can access errors by e.networkError.result.errors

comalex3
  • 2,497
  • 4
  • 26
  • 47
  • This answer helped me after spending 3 hours googling how to access graphQLErrors object from response. This should be in official Apollo docs. – Shimi Shimson May 15 '21 at 22:49
0

As I understand it, the 'catch' will catch errors if your server returns an error code, but not if it returns your errors in the response, but with a success code. In that case, you just need to get your errors out of the response (keeping your catch too in case the server responds with an error code):

this.props.mutate({
  mutation: CHANGE_ORDER_MUTATION,
    variables: {
      ids,
    },
  })
  .then((response) => {
    if (response.errors) {
      // do something with the errors
    } else {
      // there wasn't an error
    }
  })
  .catch((e) => {
    console.log(e.graphQLErrors) <--- e.graphQLErrors is always empty array = []
  })

Alternatively - if you use the graphql() option from react-apollo, you can specify an onError handler:

export default graphql(CHANGE_ORDER_MUTATION, {
  options: (props) => ({
    onCompleted: props.onCompleted,
    onError: props.onError
  }),
})(MyComponent);

references:

MorganIsBatman
  • 1,000
  • 8
  • 13