Handle GraphQL errors in client
Handle GraphQL errors in a client by checking the errors array and its extensions code, since a failed query can still return HTTP 200.
A GraphQL server answers 200 for most failures and reports them in an errors array. A client must look there, and the extensions.code field tells it what happened.
class GraphQLError extends Error {
constructor(errors) {
super(errors[0].message);
this.code = errors[0].extensions?.code ?? 'UNKNOWN';
this.errors = errors;
}
}
async function gql(query, variables) {
const res = await fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
const { data, errors } = await res.json();
if (errors?.length && !data) throw new GraphQLError(errors);
return { data, errors };
}
globalThis.fetch = async () =>
Response.json({
errors: [{ message: 'Not signed in', extensions: { code: 'UNAUTHENTICATED' } }],
});
try {
await gql('{ me { name } }');
} catch (err) {
console.log(err.code, '-', err.message);
}UNAUTHENTICATED - Not signed inThe client throws when there are errors and no data, and returns both when the response is partial, so a screen can show what loaded and flag the rest. The code comes from extensions, a free-form object that servers use for machine-readable details; Apollo Server uses codes like UNAUTHENTICATED.
Transport errors, such as a 502 from a proxy, are different: the body is not GraphQL, so check res.ok before res.json() in real code. The response format is covered in the GraphQL spec section on errors.