Albert Lyubarsky
Albert Lyubarsky

Reputation: 450

Propagate ApolloError to client

I have real hard time to get custom Apollo error on the client side.

Here is the server code:

...
const schema = makeExecutableSchema({
  typeDefs: [constraintDirectiveTypeDefs, ...typeDefs],
  resolvers,
  schemaTransforms: [constraintDirective()],
});


const server = new ApolloServer({
  schema,
  dataSources,
  context({ req }) {
    const token = req.headers.authorization;

    const user = token ? getUserFromToken(token) : '';

    return { user };
  },

  debug: false,
  formatError: (err) => { 
    // ToDo: Generate unique token and log error
    if (err!.extensions!.code == 'INTERNAL_SERVER_ERROR') {
      return new ApolloError('We are having some trouble', 'ERROR', {
        token: 'uniquetoken',
      });
    }
    return err;
  },
  uploads: false,
});
...

Client code:

 ...
const ADD_CLAIM = gql`
  mutation addClaim($claim: ClaimInput!) {
    addClaim(claim: $claim) {
      id
    }
  }
`;
...

 const [addClaim, { data, error }] = useMutation(ADD_CLAIM);

 ...

 const onSubmit = async () => {
   try {
    debugger;
    const r = await addClaim({
      variables: {
        input: {
          id: insured.insured,
          date: '20/12/2020',
      ...
          therapy: treatment.treatments.map(treat => ({
            id: treat.treatId,
        ...
          })),
        },
      },
    });

    debugger;

    console.log('r', r);

    } catch (err) {
      debugger;
      setFormError(error ? error.message : err.message);
      console.log('Error:', err);
    }
  };

...


  if (error) {
    debugger;
    return <div>error</div>;
  }

I expect to get the custom error : "We are having some trouble". However, no matter what I do I got: "Response not successful: Received status code 400"

I am 100% give custom error from the server: enter image description here

But I receive on client side: enter image description here

Moreover, when I check network tab of Developer Tools, response I do have my error: enter image description here

But I cannot access it from the code. BTW, in the playground I see my error: enter image description here

Upvotes: 1

Views: 3345

Answers (1)

Albert Lyubarsky
Albert Lyubarsky

Reputation: 450

Here where are my errors :

error.networkError.result.errors

What nobody knows ?

Or

const errorLink = onError(({ graphQLErrors, networkError }) => {
  debugger;
  console.log(graphQLErrors);
  console.log(networkError);
});

const client = new ApolloClient({
  ...
  link: ApolloLink.from( [errorLink, ...]),    
});

It works as well.

Yes, sometimes GraphQL is a nasty beast

Upvotes: 3

Related Questions