GR

GraphQL Error Handling

GraphQL error propagation, error extensions, and partial response patterns

Details

Language / Topic
graphqlGraphQL
Category
Error Handling

Rules

balanced
- Throw `GraphQLError` with a structured `extensions` object: `{ code: 'NOT_FOUND', field: 'userId' }` so clients can handle errors programmatically.
- Never expose internal server errors to clients — catch unexpected exceptions in a `formatError` hook and return a generic `INTERNAL_SERVER_ERROR` code.
- Use the `errors` array in the response alongside `data` for user-facing validation failures — return partial data when some resolvers succeed.
- Define a consistent error code enum (`NOT_FOUND`, `UNAUTHORIZED`, `VALIDATION_ERROR`, `RATE_LIMITED`) and document it in the schema or API changelog.
- Use Apollo Server's `ApolloServerErrorCode` constants for standard error codes; extend with custom codes for domain-specific errors.
- Return `UserError` types in mutation payloads for business logic failures rather than throwing — keep the HTTP status 200 and use the `errors` field.
- Log unexpected errors server-side with request ID and trace context before masking them from the client response.