Skip to content

Question about error handling migration from Apollo Client v3 to v4Β #12888

@sirconan

Description

@sirconan

Hello πŸ‘‹

I'm currently upgrading Apollo Client from v3.14.4 to v4.0.0 in
my Next.js (14.4.0) application.
I have a question about the new error handling behavior --- there's
something I don't fully understand, and maybe you could help me.


Context (Apollo v3.14.4)

I used to handle mutation errors with the onError callback
only, for example:

import { useMutation } from '@apollo/client';

const MyComponent = () => {
  const [mutate] = useMutation(MY_MUTATION);

  const handleClick = () => {
    mutate({
      variables: { id: 1 },
      onCompleted(data) {
        console.log('Mutation completed:', data);
      },
      onError(error) {
        console.error('Mutation error:', error);
      },
    });
  }

  return <button onClick={handleClick}>Run Mutation</button>;
}

Example use case:
If there is a GraphQL error, I want to catch with the onError callback.


Issue after migration to v4

After migrating to Apollo Client v4, the application throws the
error instead of handling it only in onError.

The only workaround I found is to add a .catch block in addition to
onError:

import { useMutation } from '@apollo/client';

const MyComponent = () => {
  const [mutate] = useMutation(MY_MUTATION);

  const handleClick = () => {
    mutate({
      variables: { id: 1 },
      onCompleted(data) {
        console.log('Mutation completed:', data);
      },
      onError(error) {
        console.error('Mutation error:', error);
      },
    }).catch((error) => console.error(error));
  }

  return <button onClick={handleClick}>Run Mutation</button>;
};

Question

πŸ‘‰ Is there a way in Apollo Client v4 to handle these errors
only through onError, without having to add a .catch?
Or is this the new expected behavior with mutations in v4?

For context, I'm using the default mutation setting:

{ errorPolicy: 'none' }

Thanks a lot for your amazing work on Apollo πŸš€ --- the library is
really powerful and a huge help in building production apps!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions