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.
More GraphQL Questions
View all →- Advanced What is Apollo Federation v2 and how does the supergraph work?
- Advanced How do you implement entity resolution in Apollo Federation?
- Advanced What are the security vulnerabilities specific to GraphQL?
- Advanced How does the GraphQL query planning and execution pipeline work?
- Advanced What is the @defer and @stream directive and how do they work?