Docs
Launch GraphOS Studio

Handling operation errors


can encounter a variety of errors when executing on your . Apollo Client helps you handle these errors according to their type, enabling you to show appropriate information to the user when an error occurs.

Error types

Executing on a remote server can result in

or
network errors
.

GraphQL errors

These are errors related to the server-side execution of a . They include:

  • Syntax errors (e.g., a was malformed)
  • Validation errors (e.g., a included a schema that doesn't exist)
  • Resolver errors (e.g., an error occurred while attempting to populate a )

If a syntax error or validation error occurs, your server doesn't execute the at all because it's invalid. If errors occur, your server can still return

.

Learn more about errors in the

.

If a error occurs, your server includes it in the errors array of its response to :

then adds those errors to

(or whichever hook you used).

If a error prevents from executing your at all, it responds with a 4xx status code. responds with a 200 status code if errors occurred but the response still includes

.

Partial data with resolver errors

An that produces errors might also return partial data. This means that some (but not all) of the data your requested is included in your server's response. ignores partial data by default, but you can override this behavior by

.

Network errors

These are errors encountered while attempting to communicate with your , usually resulting in a 4xx or 5xx response status code (and no data).

When a network error occurs, adds it to

(or whichever hook you used).

You can add retry logic and other advanced network error handling to your application with

.

GraphQL error policies

If a produces one or more

, your server's response might still include partial data in the data :

{
"data": {
"getInt": 12,
"getString": null
},
"errors": [
{
"message": "Failed to get string!"
// ...additional fields...
}
]
}

By default, throws away partial data and populates

(or whichever hook you're using). You can instead use these partial results by defining an error policy for your .

supports the following error policies for an :

PolicyDescription
noneIf the response includes GraphQL errors, they are returned on error.graphQLErrors and the response data is set to undefined even if the server returns data in its response. This means network errors and GraphQL errors result in a similar response shape. This is the default error policy.
ignoregraphQLErrors are ignored (error.graphQLErrors is not populated), and any returned data is cached and rendered as if no errors occurred.
allBoth data and error.graphQLErrors are populated, enabling you to render both partial results and error information.

Setting an error policy

Specify an error policy in the options object you provide your hook (such as useQuery), like so:

const MY_QUERY = gql`
query WillFail {
badField # This field's resolver produces an error
goodField # This field is populated successfully
}
`;
function ShowingSomeErrors() {
const { loading, error, data } = useQuery(MY_QUERY, { errorPolicy: "all" });
if (loading) return <span>loading...</span>;
return (
<div>
<h2>Good: {data.goodField}</h2>
<pre>
Bad:{" "}
{error.graphQLErrors.map(({ message }, i) => (
<span key={i}>{message}</span>
))}
</pre>
</div>
);
}

This example uses the all error policy to render both partial data and error information whenever applicable.

The

library enables you to configure advanced handling of errors that occur while executing .

As a recommended first step, you can add an

to your
link chain
that receives error details and acts on them accordingly.

The example below passes the ApolloClient constructor a link chain with two links:

  • An onError link that checks for graphQLErrors or a networkError in the server's response. It logs the details of whichever error(s) it finds.
  • An HttpLink that sends each to your server.

Retrying operations

helps you retry failed that might be resolved by a followup attempt. We recommend different links depending on the type of error that occurred:

On GraphQL errors

The onError link can retry a failed based on the type of error that's returned. For example, when using token-based authentication, you might want to automatically handle re-authentication when the token expires.

To retry an , you return forward(operation) in your onError function. Here's an example:

onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.code) {
// Apollo Server sets code to UNAUTHENTICATED
// when an AuthenticationError is thrown in a resolver
case "UNAUTHENTICATED":
// Modify the operation context with a new token
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: getNewToken(),
},
});
// Retry the request, returning the new observable
return forward(operation);
}
}
}
// To retry on network errors, we recommend the RetryLink
// instead of the onError link. This just logs the error.
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
});

If your retried also results in errors, those errors are not passed to your onError link to prevent an infinite loop of . This means that an onError link can retry a particular only once.

If you don't want to retry an , your onError link's function should return nothing.

On network errors

To retry that encounter a network error, we recommend adding a RetryLink to your link chain. This link enables you to configure retry logic like exponential backoff and total number of attempts.

See the

.

See the

.

Previous
Directives
Next
Document transforms
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company