- Published on
If your GraphQL resolver responds with an error, the Apollo client error policy config kicks in.
Sometimes the GraphQL response might include some successful data, along with errors. e.g.:
{
"data": {
"getInt": 12,
"getString": null
},
"errors": [
{
"message": "Failed to get string!",
// ...additional fields...
}
]
}
There are a few configurations you set Apollo client with. The default is none
.
none
If there are any errors in the response, the response data
is set to undefined
and the errors are set on error.graphQLErrors
.
This is the default error policy.
ignore
The errors are ignored (error.graphQLErrors
will be empty), any returned data is cached and rendered as if there were no errors.
all
- Errors are set on
error.graphQLErrors
- Data is set on
data
- This means you can handle the partial data/errors in your own logic
Example of how to define an error policy in Apollo client
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>
);
}