Build a comprehensive error handling and input validation system for GraphQL APIs with typed errors, user-friendly messages, and proper error classification.
## ROLE
You are a GraphQL API reliability engineer who designs robust error handling and validation systems. You understand the nuances of GraphQL error responses, partial data scenarios, and how to create developer-friendly error experiences that also work well for frontend applications.
## OBJECTIVE
Design and implement a comprehensive error handling and validation framework that provides clear, actionable errors to clients while maintaining security and enabling effective debugging.
## TASK
Build a complete error handling and validation system:
### Error Classification System
**1. Error Type Hierarchy**
- User errors (validation, not found, unauthorized, forbidden)
- System errors (database, external service, timeout)
- Business logic errors (insufficient funds, quota exceeded, conflict)
- GraphQL-specific errors (query complexity, depth limit, rate limit)
**2. Error Response Design**
**Approach A: Top-Level Errors (Standard GraphQL)**
```json
{
"errors": [{
"message": "User-friendly message",
"extensions": {
"code": "VALIDATION_ERROR",
"field": "email",
"details": [...]
},
"path": ["createUser"]
}],
"data": { "createUser": null }
}
```
**Approach B: Typed Error Unions (Result Pattern)**
```graphql
union CreateUserResult = CreateUserSuccess | ValidationError | NotFoundError
type CreateUserSuccess { user: User! }
type ValidationError { fields: [FieldError!]! }
```
- Comparison of approaches with trade-offs
- Recommendation based on use case
- Hybrid approach for complex applications
### Input Validation Framework
**1. Schema-Level Validation**
- Custom scalar validators (Email, URL, PhoneNumber, etc.)
- Input type constraints and patterns
- Required vs. optional field handling
- Custom validation directives (@constraint, @length, @pattern)
**2. Resolver-Level Validation**
- Validation library integration (Joi, Yup, Zod)
- Validation schema co-location with GraphQL types
- Cross-field validation patterns
- Async validation (uniqueness checks, external verification)
- Validation error aggregation (return all errors, not just first)
**3. Business Rule Validation**
- Domain-specific validation in service layer
- Contextual validation (rules that depend on current state)
- Permission-based validation differences
- Conditional required fields
### Error Formatting & Sanitization
**Production Error Handling**
- Masking internal errors from client responses
- Error logging with full context (user, query, variables)
- Stack trace handling (show in dev, hide in prod)
- Sensitive data scrubbing from error messages
- Correlation IDs for error tracking
**Error Monitoring Integration**
- Sentry/DataDog/New Relic integration patterns
- Custom error grouping rules
- Alert thresholds and escalation
- Error rate dashboards
### Partial Success Patterns
- Handling nullable fields with errors
- Batch mutation partial success/failure
- Graceful degradation when external services fail
- Fallback data strategies
- Client-side error boundary integration
### Testing Error Scenarios
- Error response snapshot testing
- Validation rule unit testing
- Error formatting integration tests
- Chaos engineering for error resilience
- Error documentation and client SDK generationOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
{
"errors": [{
"message": "User-friendly message",
"extensions": {
"code": "VALIDATION_ERROR",
"field": "email",
"details": [...]
}{ "createUser": null }{ user: User! }{ fields: [FieldError!]! }