⬡ GraphQL Advanced

What are the best practices for error handling in GraphQL APIs?

Answer

Production GraphQL error handling best practices: (1) Typed user errors: use the "errors-as-data" pattern for expected business errors — return them in the payload rather than the top-level errors array: type CreateUserPayload { user: User errors: [UserError!] }. Reserve top-level errors for unexpected/system errors. (2) Error codes: always include machine-readable codes in extensions.code: UNAUTHENTICATED, FORBIDDEN, NOT_FOUND, VALIDATION_ERROR. (3) Mask internal errors: never expose stack traces, SQL queries, or internal messages to clients — log them server-side, return generic messages. (4) Logging: log all resolver errors with context (user ID, operation name, variables). (5) Error boundaries: use null propagation behavior intentionally — design nullable vs non-null fields to control error impact scope. (6) Client error handling: always check both data and errors — Apollo's errorPolicy: 'all' returns partial data alongside errors.