error Policy in Apollo Client React does'nt work

962 views Asked by At

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please! Here my code:

query { animal { name age }, school { name numberfd } } `

const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, { errorPolicy:'all', onCompleted: (res) => {console.log("complete",res)}, onError : (res,data) => {console.log("ERRRR",res,data)}, })

and i want to receive:

{ error:[...], data:[animal:[...]] }

but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/

2

There are 2 answers

0
Ilya Kushlianski On

I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.

I created an ErrorLink like this:

private createErrorLink = () => {
    return new ApolloLink((operation, forward) => {
      return forward(operation).map((response) => {
        // filter out errors you don't want to display

        const errors = filterSomeErrors(response.errors);        

        if (errors && response?.data) {
          response.data.errors = errors;
        }

        return response;
      });
    });
  };

Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.

Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

0
mr__brainwash On

onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback. After useQuery you can add:

console.log('data', data)
console.log('error', error)