API-85Recommended
Give every GraphQL error a stable code
Put a fixed, documented code such as NOT_FOUND or FORBIDDEN in extensions.code of every GraphQL error. Clients act on the code, never on the message text.
How to do it
GraphQL answers with HTTP 200 for many failures, so the status code tells a client little. The specification reserves extensions in each error for extra data. Keep the list of codes in the schema docs. Treat a new code as an additive change, as keep error types stable says for REST. Some failures are part of the normal flow, such as a taken username. Return those as a typed result in the schema instead. Hide internals as hide internals in errors says.
Examples
JavaScript example
import { GraphQLError } from 'graphql';
throw new GraphQLError('Invoice not found', { extensions: { code: 'NOT_FOUND' } });
Python example
from graphql import GraphQLError
raise GraphQLError("Invoice not found", extensions={"code": "NOT_FOUND"})
How to check
A test triggers each documented failure and reads errors[0].extensions.code. Each matches the documented code. A forced server crash returns INTERNAL_SERVER_ERROR with no stack trace.
Sources
Related rules
- API-17 Keep error types stable in API design
- API-19 Hide internals in errors in API design
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/graphql-and-grpc/graphql-error-codes">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.