Why graphQLErrors are always empty in react components?
Asked Answered
R

2

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 });

Resnatron answered 13/3, 2019 at 17:27 Comment(0)
R
7

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

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

Resnatron answered 3/4, 2019 at 9:10 Comment(1)
This answer helped me after spending 3 hours googling how to access graphQLErrors object from response. This should be in official Apollo docs.Conchiolin
S
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:

Stage answered 14/3, 2019 at 2:54 Comment(2)
server returns status 500. Also I able to access graphQLErrors errors by error.networkError.result.errorsResnatron
so you've found what you were looking for then?Stage

© 2022 - 2024 — McMap. All rights reserved.