Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

gql-errors.jsJavaScript
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);
}
Text
UNAUTHENTICATED - Not signed in

The 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.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.