Structured GraphQL Errors with Extension Codes
Implement structured error handling in GraphQL with custom error classes, extension codes, and consistent error formatting for clients.
GraphQL errors are plain objects with a message field, which is why many clients end up matching on message text to decide what went wrong. Attaching a machine-readable extensions.code gives clients a stable contract, and extra extension fields can carry validation details, retry hints, or the affected field. This recipe builds that error system end to end for Apollo Server: typed error classes, safe formatting, and client-side handling. For the underlying concept, see the GraphQL error extension pattern.
When to Use This
- GraphQL APIs consumed by web, mobile, and third-party clients at once
- APIs where clients must branch on error type programmatically (retry, redirect to login, show field errors)
- Services that need to tell validation, auth, not-found, and server errors apart
Skip this when the API has a single consumer you control and error responses are only inspected by humans. For REST-style problem details, see Handle API Errors with RFC 7807.
Prerequisites
- Apollo Server 4+ (the
formatErrorsignature differs from v3) - Basic familiarity with GraphQL error responses (
data+errors)
Solution
1. Define Error Codes
// errors/codes.ts
export const ErrorCodes = {
VALIDATION_ERROR: 'VALIDATION_ERROR',
UNAUTHENTICATED: 'UNAUTHENTICATED',
FORBIDDEN: 'FORBIDDEN',
NOT_FOUND: 'NOT_FOUND',
CONFLICT: 'CONFLICT',
RATE_LIMITED: 'RATE_LIMITED',
} as const;
export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
Keep the list short. A code is a contract: every value you publish is one more case clients have to handle.
2. Create a Base Error Class
// errors/base.ts
import { GraphQLError } from 'graphql';
import { ErrorCodes, type ErrorCode } from './codes';
export class AppError extends GraphQLError {
constructor(message: string, code: ErrorCode, extensions?: Record<string, unknown>) {
super(message, { extensions: { code, ...extensions } });
}
}
export class ValidationError extends AppError {
constructor(errors: { field: string; message: string }[]) {
super('Input validation failed', ErrorCodes.VALIDATION_ERROR, { errors });
}
}
export class AuthenticationError extends AppError {
constructor(message = 'Authentication required') {
super(message, ErrorCodes.UNAUTHENTICATED);
}
}
export class ForbiddenError extends AppError {
constructor(message = 'Insufficient permissions', requiredRole?: string) {
super(message, ErrorCodes.FORBIDDEN, { requiredRole });
}
}
export class NotFoundError extends AppError {
constructor(resource: string, id: string) {
super(`${resource} not found`, ErrorCodes.NOT_FOUND, { resource, id });
}
}
export class ConflictError extends AppError {
constructor(message: string, conflicts?: Record<string, unknown>) {
super(message, ErrorCodes.CONFLICT, { conflicts });
}
}
export class RateLimitError extends AppError {
constructor(retryAfter: number) {
super('Rate limit exceeded', ErrorCodes.RATE_LIMITED, { retryAfter });
}
}
3. Throw Errors from Resolvers
// resolvers.ts
import {
ValidationError,
NotFoundError,
AuthenticationError,
ForbiddenError,
ConflictError,
} from './errors/base';
interface Context {
user: { id: string; role: string } | null;
db: {
posts: {
findById(id: string): Promise<Post | null>;
findBySlug(slug: string): Promise<Post | null>;
create(data: CreatePostInput & { authorId: string }): Promise<Post>;
};
};
}
interface CreatePostInput {
title: string;
content: string;
slug: string;
}
export const resolvers = {
Query: {
post: async (_: unknown, { id }: { id: string }, ctx: Context) => {
if (!ctx.user) throw new AuthenticationError();
const post = await ctx.db.posts.findById(id);
if (!post) throw new NotFoundError('Post', id);
if (post.authorId !== ctx.user.id && ctx.user.role !== 'admin') {
throw new ForbiddenError('You can only view your own posts', 'admin');
}
return post;
},
},
Mutation: {
createPost: async (_: unknown, { input }: { input: CreatePostInput }, ctx: Context) => {
if (!ctx.user) throw new AuthenticationError();
const errors = validatePostInput(input);
if (errors.length > 0) throw new ValidationError(errors);
const existing = await ctx.db.posts.findBySlug(input.slug);
if (existing) throw new ConflictError('Slug already exists', { slug: input.slug });
return ctx.db.posts.create({ ...input, authorId: ctx.user.id });
},
},
};
function validatePostInput(input: CreatePostInput): { field: string; message: string }[] {
const errors: { field: string; message: string }[] = [];
if (!input.title || input.title.length < 3) {
errors.push({ field: 'title', message: 'Title must be at least 3 characters' });
}
if (!input.content || input.content.length < 10) {
errors.push({ field: 'content', message: 'Content must be at least 10 characters' });
}
return errors;
}
4. Configure formatError in Apollo Server 4
In Apollo Server 4, formatError receives (formattedError, error). The structured fields from your GraphQLError already live on formattedError.extensions; the second argument is the original thrown error, possibly wrapped. Use unwrapResolverError to inspect it:
// server.ts
import { ApolloServer } from '@apollo/server';
import { ApolloServerErrorCode, unwrapResolverError } from '@apollo/server/errors';
const server = new ApolloServer<Context>({
typeDefs,
resolvers,
includeStacktraceInErrorResponses: process.env.NODE_ENV !== 'production',
formatError: (formattedError, error) => {
// Deliberate errors carry our own code: let them through untouched.
if (formattedError.extensions?.code !== ApolloServerErrorCode.INTERNAL_SERVER_ERROR) {
return formattedError;
}
// Apollo already normalized this to INTERNAL_SERVER_ERROR, but the
// original message still leaks. Mask it and log the real error.
console.error('Unhandled resolver error:', unwrapResolverError(error));
return {
message: 'Internal server error',
extensions: { code: ApolloServerErrorCode.INTERNAL_SERVER_ERROR },
};
},
});
Two details matter here. First, formattedError.extensions preserves whatever GraphQLError put there, so deliberate errors pass through untouched. Second, Apollo Server 4 normalizes any unexpected throw to INTERNAL_SERVER_ERROR before formatError runs, but keeps the original TypeError message (and stacktrace in dev). The callback above is where you replace that leaked message with a generic one and log unwrapResolverError(error) for the real cause. includeStacktraceInErrorResponses controls whether extensions.stacktrace reaches clients; turn it off in production.
5. Handle Errors on the Client
// client.ts
interface CreatePostInput {
title: string;
content: string;
slug: string;
}
const CREATE_POST_MUTATION = /* GraphQL */ `
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) { id title slug }
}
`;
async function createPost(input: CreatePostInput) {
const response = await fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: CREATE_POST_MUTATION, variables: { input } }),
});
const { data, errors } = await response.json();
if (errors?.length) {
for (const error of errors) {
switch (error.extensions?.code) {
case 'VALIDATION_ERROR':
showFieldErrors(error.extensions.errors);
break;
case 'UNAUTHENTICATED':
window.location.href = '/login';
break;
case 'FORBIDDEN':
showToast('You need additional permissions');
break;
case 'RATE_LIMITED':
scheduleRetry(error.extensions.retryAfter);
break;
case 'NOT_FOUND':
case 'CONFLICT':
showToast(error.message);
break;
default:
showToast('Something went wrong. Please try again.');
}
}
return null;
}
return data.createPost;
}
How It Works
AppErrorwrapsGraphQLErrorand forces acodeintoextensions, so every deliberate error carries a machine-readable category.- Specialized classes add domain context (
errorsfor validation,retryAfterfor rate limits,resource/idfor not-found) on top of the shared shape. formatErroris the safety net: deliberate errors pass through with their codes; Apollo normalizes unexpected exceptions toINTERNAL_SERVER_ERROR, and the callback masks the leaked message and logs the real cause. See the Apollo Server error docs for the fullformatErrorcontract.- Clients switch on
extensions.code, which survives message rewording, localization, and refactoring.
The codes above map cleanly onto what a client should do with them:
| Code | Means | Typical client action |
|---|---|---|
VALIDATION_ERROR | Input failed field checks | Highlight the offending fields |
UNAUTHENTICATED | No valid credential | Redirect to login or refresh token |
FORBIDDEN | Valid credential, wrong permissions | Show access denied, offer upgrade |
NOT_FOUND | Resource doesn’t exist | Render empty state |
CONFLICT | Write clashes with existing data | Prompt the user to resolve it |
RATE_LIMITED | Too many requests | Retry after retryAfter seconds |
INTERNAL_SERVER_ERROR | Unexpected server failure | Generic error UI, alert on-call |
Variants
Error Logging Plugin
Log unexpected errors with structured metadata while clients get the masked response:
// plugins/error-logger.ts
import type { ApolloServerPlugin } from '@apollo/server';
import { ApolloServerErrorCode, unwrapResolverError } from '@apollo/server/errors';
const errorLogger: ApolloServerPlugin = {
async requestDidStart() {
return {
async didEncounterErrors(ctx) {
for (const error of ctx.errors) {
if (error.extensions?.code === ApolloServerErrorCode.INTERNAL_SERVER_ERROR) {
logger.error({
operation: ctx.operationName,
path: error.path,
err: unwrapResolverError(error),
});
}
}
},
};
},
};
Union Types for Expected Outcomes
When a failure is a normal domain result rather than an exception, model it in the schema:
union CreatePostResult = Post | ValidationError | SlugTakenError
type ValidationError {
field: String!
message: String!
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostResult!
}
// resolvers.ts (excerpt)
CreatePostResult: {
__resolveType(obj: Post | { field: string }) {
return 'field' in obj ? 'ValidationError' : 'Post';
},
},
Clients get typed branches with no try/catch. The trade-off: every mutation needs its own union type, so reserve this for outcomes the UI must render differently. For related batching concerns, see Fix N+1 Queries in GraphQL Resolvers.
Best Practices
- Always set
extensions.code. It’s the contract between server and client; messages are for humans, codes are for programs. - Mask unexpected errors in
formatError. Database errors, file paths, and stack traces leak implementation details. - Log the real error server-side. Clients see a generic message; your logs keep the full trace.
- Write actionable messages. Tell the client what to fix, not just what broke.
- Distinguish
UNAUTHENTICATEDfromFORBIDDEN. The first means no valid credential; the second means valid credential, wrong permissions. Clients handle them differently (redirect vs. toast).
Common Mistakes
- Using HTTP status codes for GraphQL errors. GraphQL returns 200 with errors in the body; transport failures are a separate concern.
- Throwing plain
Error. Withoutextensions.codeattached, clients fall back to string matching. - Exposing internal messages. A raw
PrismaClientKnownRequestErrortells attackers your ORM, schema, and sometimes data. - Overloading
INTERNAL_SERVER_ERROR. If a failure is expected (not found, conflict), give it its own code so clients can distinguish it from real bugs. - Non-null fields where errors can happen. A field that throws propagates
nullupward and can wipe out the whole response; prefer nullable fields where partial data is still useful. The GraphQL spec’s error section defines this bubbling behavior.
Frequently Asked Questions
Should I use GraphQL errors or union types for expected failures?
Use errors for exceptional situations (server failure, missing auth). Use union types when the "failure" is a normal domain outcome the UI must render: validation feedback, conflicts, not-found states. Mixing both is fine; many APIs throw for auth/server issues and return unions for domain results.
How do I test error responses?
Assert on errors[0].extensions.code, not on the message text:
const res = await request(app).post('/graphql').send({ query, variables });
expect(res.body.errors[0].extensions.code).toBe('VALIDATION_ERROR');
expect(res.body.errors[0].extensions.errors).toContainEqual({
field: 'title',
message: expect.any(String),
});
Message text changes with wording and localization; codes are the stable contract.
What goes in extensions besides code?
Whatever clients need to act: errors (field-level validation), retryAfter, resource/id, requiredRole, http.status for gateways that map to HTTP. Extensions is an open map per the spec, but treat every field you add as public API surface.
Should I localize error messages?
Return codes and structured fields; let the client localize. A VALIDATION_ERROR with { field: 'title', minLength: 3 } can become "Title must be at least 3 characters" or "El título debe tener al menos 3 caracteres" in the UI layer, using the user's locale.
How do partial data and null bubbling work?
A GraphQL response can contain both data and errors. When a non-null field errors, its value nullifies upward until it hits a nullable field or the root. Design the schema so fields that can realistically fail are nullable; reserve ! for fields where failure should genuinely invalidate the parent.
What is the difference between UNAUTHENTICATED and FORBIDDEN?
UNAUTHENTICATED means the request has no valid credential (roughly HTTP 401): the client should redirect to login or refresh the token. FORBIDDEN means the credential is valid but lacks permission (roughly HTTP 403): show an access-denied message, optionally naming extensions.requiredRole.
Related Resources
GraphQL Error Extension Pattern
Attach structured metadata to GraphQL errors using extension codes for predictable client-side error handling.
RecipeValidate and Sanitize GraphQL Input Types Server-Side
Implement centralized input validation in GraphQL using Zod schemas, input type transforms, and structured field-level errors
RecipeBuild a GraphQL API with Apollo Server and TypeScript
How to build a production-ready GraphQL API using Apollo Server, TypeScript, and DataLoader to solve the N+1 query problem
RecipeHandle API Errors with RFC 7807 and HTTP Status Codes
Patterns for consistent, predictable API error handling across multiple languages and frameworks.
RecipeField-Level Auth with Custom GraphQL Directives
Add field-level authorization to GraphQL with custom schema directives. Check roles, permissions, and ownership per field in Apollo Server.
RecipeMock GraphQL Resolvers for Frontend Development
Set up mocked GraphQL resolvers with Apollo Server so frontend teams can develop against a fake API before the backend is ready.