StackPractices
intermediate By Mathias Paulenko

GraphQL Error Extension Pattern

Attach structured metadata to GraphQL errors using extension codes for predictable client-side error handling.

Overview

GraphQL errors come back as a list of { message, locations, path } objects. The message field is a human-readable string, but clients need machine-readable codes to handle errors programmatically. The error extension pattern attaches structured metadata to errors via the extensions field — error codes, HTTP status equivalents, field paths, and context — so clients can branch on code instead of parsing message.

When to Use

  • Any GraphQL API where clients need to handle errors programmatically (show different UI for auth vs validation vs not-found)
  • APIs consumed by mobile apps or other services that need stable error contracts
  • Multi-language clients where parsing English error messages is fragile
  • APIs that need to report validation errors with field-level details

When Not to Use

  • Internal tools where the default message is sufficient
  • Prototypes or throwaway APIs where error handling isn’t a priority

Solution

1. Define Error Codes

Use a consistent enum of error codes across the entire API:

const ErrorCodes = {
  UNAUTHENTICATED: 'UNAUTHENTICATED',
  FORBIDDEN: 'FORBIDDEN',
  NOT_FOUND: 'NOT_FOUND',
  VALIDATION_ERROR: 'VALIDATION_ERROR',
  BAD_USER_INPUT: 'BAD_USER_INPUT',
  INTERNAL_ERROR: 'INTERNAL_ERROR',
  RATE_LIMITED: 'RATE_LIMITED',
  CONFLICT: 'CONFLICT',
} as const;

type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];

2. Custom Error Class

import { GraphQLError } from 'graphql';

class GraphQLExtendedError extends GraphQLError {
  constructor(
    message: string,
    code: ErrorCode,
    extensions: Record<string, unknown> = {}
  ) {
    super(message, {
      extensions: {
        code,
        ...extensions,
      },
    });
  }
}

3. Throwing Structured Errors in Resolvers

const resolvers = {
  Query: {
    post: async (_parent, { id }, { db, user }) => {
      if (!user) {
        throw new GraphQLExtendedError(
          'Authentication required',
          ErrorCodes.UNAUTHENTICATED,
          { http: { status: 401 } }
        );
      }

      const post = await db.post.findById(id);
      if (!post) {
        throw new GraphQLExtendedError(
          `Post ${id} not found`,
          ErrorCodes.NOT_FOUND,
          { resourceId: id, http: { status: 404 } }
        );
      }

      if (post.authorId !== user.id && user.role !== 'admin') {
        throw new GraphQLExtendedError(
          "You don't have permission to view this post",
          ErrorCodes.FORBIDDEN,
          { http: { status: 403 } }
        );
      }

      return post;
    },
  },
  Mutation: {
    createPost: async (_parent, { input }, { db, user }) => {
      if (!user) {
        throw new GraphQLExtendedError(
          'Authentication required',
          ErrorCodes.UNAUTHENTICATED
        );
      }

      if (!input.title || input.title.trim().length === 0) {
        throw new GraphQLExtendedError(
          'Title is required',
          ErrorCodes.VALIDATION_ERROR,
          { field: 'title', constraint: 'required' }
        );
      }

      if (input.title.length > 200) {
        throw new GraphQLExtendedError(
          'Title must be 200 characters or less',
          ErrorCodes.VALIDATION_ERROR,
          { field: 'title', constraint: 'max_length', max: 200, actual: input.title.length }
        );
      }

      return db.post.create({ ...input, authorId: user.id });
    },
  },
};

4. Client-Side Error Handling

Clients branch on extensions.code instead of parsing message:

async function fetchPost(id: string) {
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: `query { post(id: "${id}") { title body } }` }),
  });

  const { data, errors } = await response.json();

  if (errors) {
    const error = errors[0];
    const code = error.extensions?.code;

    switch (code) {
      case 'UNAUTHENTICATED':
        redirectToLogin();
        return;
      case 'NOT_FOUND':
        showNotFoundPage();
        return;
      case 'FORBIDDEN':
        showAccessDenied();
        return;
      case 'VALIDATION_ERROR':
        showFieldError(error.extensions.field, error.message);
        return;
      default:
        showGenericError(error.message);
        return;
    }
  }

  return data.post;
}

5. Global Error Formatting

Use Apollo Server’s formatError to sanitize errors before they reach clients:

import { ApolloServer } from '@apollo/server';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (formattedError, error) => {
    // Never expose internal errors to clients
    if (formattedError.extensions?.code === 'INTERNAL_ERROR') {
      return {
        message: 'An internal error occurred',
        extensions: {
          code: 'INTERNAL_ERROR',
          timestamp: new Date().toISOString(),
        },
      };
    }

    // Log full error server-side, return sanitized version to client
    console.error('GraphQL Error:', {
      code: formattedError.extensions?.code,
      message: formattedError.message,
      path: formattedError.path,
      stack: error?.stack,
    });

    // Remove stack traces from client responses
    delete formattedError.extensions?.stacktrace;
    return formattedError;
  },
});

Explanation

Errors thrown inside a resolver travel through a fixed pipeline before they reach the client:

Flowchart of the GraphQL error extension pipeline: a resolver throws a GraphQLError with extensions.code, formatError sanitizes it, the response errors array carries it, and the client switches on the code

When a resolver throws, GraphQL catches the exception and places it in the errors array of the response. A NOT_FOUND error from the resolver above produces this payload:

{
  "errors": [
    {
      "message": "Post 42 not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["post"],
      "extensions": {
        "code": "NOT_FOUND",
        "resourceId": "42",
        "http": { "status": 404 }
      }
    }
  ],
  "data": { "post": null }
}

Four properties of this shape matter:

  • Error codes: Stable, machine-readable identifiers that clients can switch on. They never change even when messages are reworded
  • Extensions: The GraphQL spec defines extensions on errors as an arbitrary JSON object — use it for code, field, http.status, resourceId, or any metadata clients need
  • HTTP status: GraphQL responses always return HTTP 200, but including http.status in extensions lets gateways or middleware translate to proper HTTP codes if needed
  • Sanitization: formatError in Apollo Server runs before the response is sent — strip stack traces, rewrite internal errors, add timestamps

This shape also handles partial failures: GraphQL can return data and errors in the same response, with each error carrying a path to the field that failed. Extensions give each of those errors its own context, which is something a single HTTP status code can’t express.

Variants

Validation Error Collection

Collect every field error and return them all in a single response. For validating the inputs themselves before this point, see the GraphQL Input Validation recipe:

Mutation: {
  createPost: async (_parent, { input }, { db, user }) => {
    const errors: GraphQLError[] = [];

    if (!input.title?.trim()) {
      errors.push(new GraphQLExtendedError('Title required', ErrorCodes.VALIDATION_ERROR, { field: 'title' }));
    }
    if (!input.body?.trim()) {
      errors.push(new GraphQLExtendedError('Body required', ErrorCodes.VALIDATION_ERROR, { field: 'body' }));
    }
    if (input.tags && input.tags.length > 10) {
      errors.push(new GraphQLExtendedError('Max 10 tags', ErrorCodes.VALIDATION_ERROR, { field: 'tags', max: 10 }));
    }

    if (errors.length > 0) {
      throw new GraphQLError('Validation failed', {
        extensions: {
          code: ErrorCodes.VALIDATION_ERROR,
          errors: errors.map((e) => e.extensions),
        },
      });
    }

    return db.post.create(input);
  },
},

Error Translation by Language

const errorMessages = {
  UNAUTHENTICATED: {
    en: 'Authentication required',
    es: 'Se requiere autenticacion',
    fr: 'Authentification requise',
  },
  NOT_FOUND: {
    en: 'Resource not found',
    es: 'Recurso no encontrado',
    fr: 'Ressource introuvable',
  },
};

function createError(code: ErrorCode, lang: string, extensions: Record<string, unknown> = {}) {
  const message = errorMessages[code]?.[lang] ?? errorMessages[code]?.en ?? code;
  return new GraphQLExtendedError(message, code, extensions);
}

Rate Limit Error with Retry-After

throw new GraphQLExtendedError(
  'Rate limit exceeded. Try again in 60 seconds.',
  ErrorCodes.RATE_LIMITED,
  {
    http: { status: 429 },
    retryAfter: 60,
    limit: 100,
    remaining: 0,
  }
);

Best Practices

  • Use a fixed set of error codes — document them in the schema as a custom scalar or directive
  • Never change error code strings after release — clients depend on them
  • Always include code in extensions, even for unexpected errors
  • Strip stack traces and internal details in formatError before sending to clients
  • Log full errors server-side with request IDs for debugging
  • Include field-level details in validation errors so clients can highlight the right inputs — the GraphQL Mutation Validation pattern covers the input-checking side
  • Use INTERNAL_ERROR for unhandled exceptions — never leak database error messages
  • For a deeper guide, see Complete Guide to GraphQL Schema Design

Common Mistakes

  • Relying on message for control flow: Messages get reworded or translated, breaking client logic
  • Leaking stack traces: Default Apollo Server includes extensions.stacktrace — strip it in formatError
  • Using HTTP status codes as error codes: They’re different domains. Use semantic codes (NOT_FOUND) and optionally include HTTP status in extensions
  • Not handling unexpected errors: Wrap resolvers in try/catch or use a global error plugin to ensure every error has a code
  • Returning errors as data instead of throwing: GraphQL has a built-in errors array — use it. Clients expect errors there, not in data

Frequently Asked Questions

Should I use GraphQL errors or return error types in the schema?

Both approaches work, and they solve different problems. Thrown errors are simpler for cross-cutting concerns like auth and validation. Union return types (CreatePostResult = CreatePostSuccess | ValidationError) give type-safe error handling per field but add schema complexity. Use errors for most cases and unions where an error is part of the normal result flow — a checkout mutation that can legitimately decline a card is a good union candidate.

How do error extensions work with federation?

Federation preserves error extensions across the gateway. Subgraph errors reach the client with their extensions intact, including the subgraph name in extensions.serviceName, so client code can tell which service produced the error.

Can I localize error messages?

Yes, and the extension codes are what make it safe. Pass the user's language preference through the context, translate message in resolvers or formatError, and keep extensions.code language-independent so client logic never depends on translated strings.

What HTTP status should GraphQL errors return?

The GraphQL spec uses HTTP 200 for responses that contain errors, because errors belong to fields rather than to the transport. Some gateways translate specific error codes to HTTP 4xx/5xx for non-GraphQL-aware clients — include http.status in extensions if you need that behavior.

What belongs in extensions besides code?

Field-level details (field, constraint, max), identifiers (resourceId, requestId), retry metadata (retryAfter), and http.status for gateways. Keep extensions free of stack traces, SQL fragments, and user PII — they are part of the public response contract.

How do I signal rate limiting to clients?

Throw an error with code: 'RATE_LIMITED' and a retryAfter value in extensions, as shown in the rate limit variant. Clients read retryAfter and schedule the retry instead of parsing the message text.