Comprehensive Error Handling and Debugging Research for Claude Code
Executive Summary
This document presents comprehensive research findings on error handling and debugging strategies for Claude Code applications, gathered from the latest 2025 sources, official documentation, and production experiences. The research covers common error types, debugging strategies, error recovery patterns, logging best practices, debugging tools, common pitfalls, and production error handling approaches.
1. Common Error Types and Their Meanings
1.1 API-Related Errors
Authentication Errors (401)
- Cause: Invalid or missing API key
- Common Scenarios:
- Incorrect API key format (should start with
sk-ant-) - Expired OAuth tokens
- Missing ANTHROPIC_API_KEY environment variable
- Incorrect API key format (should start with
- Solution: Verify API key format and regenerate OAuth tokens with
claude setup-token
Rate Limit Errors (429)
- Cause: Too many requests in a short period
- Headers: Contains
retry-afterindicating wait time - Solution: Implement exponential backoff and respect retry-after headers
Network Connection Errors
- Types:
ECONNREFUSED: Connection refused (API unreachable)ETIMEDOUT: Connection timed outENOTFOUND: DNS resolution failedUNABLE_TO_GET_ISSUER_CERT_LOCALLY: SSL certificate issues
- Solution: Check network connectivity, verify API endpoints, handle NODE_EXTRA_CA_CERTS
Bad Request Errors (400)
- Cause: Invalid parameters or malformed requests
- Common Issues:
- Incorrect model names
- Invalid token counts
- Malformed JSON in requests
- Solution: Validate input parameters before sending requests
1.2 Claude Code Specific Errors
Tool Execution Errors
- Shell Snapshot Errors: Issues with Bash tool execution
- MCP Tool Errors: Multi-Component Protocol tool failures
- Path Handling Errors: Especially in WSL environments
- Solution: Use
/doctorcommand for diagnosis
Configuration Errors
- Invalid JSON: Malformed
~/.claude/settings.json - Hook Configuration: Incorrect hook patterns or event names
- Permission Issues: File access problems
- Solution: Validate JSON syntax with
jq, check file permissions
Context Window Errors
- Truncated Responses: Output cut off due to size limitations
- Context Overflow: Too much conversation history
- Solution: Use
/clearcommand, implement automatic compaction
1.3 AI-Specific Errors
Output Errors
- Truncated Responses: Incomplete generation due to token limits
- Malformed Responses: Invalid characters or formatting
- Inconsistent Output: Unexpected behavior or deviations
- Solution: Implement retry logic with fallback models
Hallucination and Accuracy Issues
- False Information: AI generating incorrect data
- Simulated Outputs: Claims of completing tasks not actually done
- Solution: Validate outputs, request specific file:line references
2. Debugging Strategies for AI-Generated Code
2.1 Systematic Debugging Approach
The Five-Step Process
- Reproduce: Consistently reproduce the issue
- Isolate: Narrow down the problem area
- Hypothesize: Form theories about the cause
- Test: Validate or invalidate hypotheses
- Fix: Implement and verify the solution
2.2 AI-Assisted Debugging Techniques
Stack Trace Analysis
// Drop stack trace into Claude
"My React app crashes when trying to read 'email' from an API response.
Here's the stack trace: [paste stack trace]
How can I handle undefined properties safely?"Log Analysis Pattern
# Copy logs and analyze
"Analyze this error in the context of our authentication system:
[paste error logs]"Using Extended Thinking Mode
- Trigger words for complex debugging:
- “think” - Basic extended thinking
- “think hard” - More computation time
- “think harder” - Even more time
- “ultrathink” - Maximum thinking budget
2.3 CLAUDE.md for Context
The /init Command
- Analyzes entire codebase
- Generates CLAUDE.md file as project memory
- Provides context for better debugging suggestions
Continuous Improvement
# CLAUDE.md
## Common Errors and Solutions
- Error: [specific error]
Solution: [how to fix]
Prevention: [how to avoid]3. Error Recovery Patterns
3.1 Retry Patterns
Exponential Backoff
class RetryHandler {
async retryWithBackoff<T>(
operation: () => Promise<T>,
maxRetries: number = 3
): Promise<T> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
if (attempt === maxRetries - 1) throw error;
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error('Max retries exceeded');
}
}Rate Limit Aware Retry
async function handleRateLimit(error: Anthropic.RateLimitError) {
const retryAfter = parseInt(error.headers?.['retry-after'] || '60');
console.log(`Rate limited. Waiting ${retryAfter} seconds...`);
await sleep(retryAfter * 1000);
}3.2 Fallback Strategies
Model Fallback Pattern
const models = [
'claude-opus-4-20250514',
'claude-sonnet-4-20250514',
'claude-haiku-4-20250514'
];
for (const model of models) {
try {
return await query({ prompt, model });
} catch (error) {
console.error(`Failed with ${model}:`, error);
}
}Graceful Degradation
- Reduce token limits on failure
- Simplify prompts automatically
- Fall back to simpler operations
3.3 Circuit Breaker Pattern
class CircuitBreaker {
private failures = 0;
private state: 'closed' | 'open' | 'half-open' = 'closed';
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === 'open') {
throw new Error('Circuit breaker is open');
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
}3.4 Atomic Operations
Configuration Safety
- Use atomic writes for config files
- Implement validation before save
- Keep backups of working configs
Batch Processing with Error Handling
BatchTool(
Bash("npm run lint"),
Bash("npm run test"),
Bash("npm run security-scan")
)4. Logging and Error Tracking Best Practices
4.1 Structured Logging
Comprehensive Error Context
interface ErrorContext {
timestamp: Date;
errorType: string;
message: string;
stackTrace: string[];
environment: Record<string, any>;
requestId?: string;
userId?: string;
sessionId?: string;
}Log Levels and Categories
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)4.2 OpenTelemetry Integration
Basic Setup
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317Key Metrics to Track
- Active sessions and concurrent agents
- Token usage and costs by model
- Tool performance and success rates
- Latency and error rates
- Lines of code changed
- Commit and PR metrics
4.3 Real-time Monitoring
Event Monitoring Pattern
class EventMonitor:
def __init__(self):
self.events = deque(maxlen=100)
self.error_threshold = 0.1 # 10% error rate
async def process_event(self, event):
self.events.append(event)
if self.calculate_error_rate() > self.error_threshold:
await self.alert_on_high_error_rate()Cost Tracking
class CostTracker:
TOKEN_COSTS = {
'claude-3-opus': {'input': 0.015, 'output': 0.075},
'claude-3-sonnet': {'input': 0.003, 'output': 0.015},
'claude-3-haiku': {'input': 0.00025, 'output': 0.00125}
}5. Debugging Tools and Techniques
5.1 Built-in Claude Code Tools
The /doctor Command
- Diagnoses installation issues
- Validates configuration files
- Checks API connectivity
- Fixes common problems automatically
Debug Flags
# Verbose output
claude --verbose
# MCP debugging
claude --mcp-debug
# Enable all telemetry
export ANTHROPIC_LOG=debugThe /bug Command
- Report issues directly from Claude Code
- Automatically collects context
- Sends to Anthropic for analysis
5.2 Hook-Based Debugging
Debug Logger Hook
#!/bin/bash
LOG_FILE="$HOME/.claude/debug.log"
JSON_INPUT=$(cat)
{
echo "=== [$(date -u +%Y-%m-%dT%H:%M:%SZ)] Hook Debug ==="
echo "Event: $CLAUDE_HOOK_EVENT"
echo "Tool: $CLAUDE_TOOL_NAME"
echo "JSON Input:"
echo "$JSON_INPUT" | jq '.'
} >> "$LOG_FILE"
echo "$JSON_INPUT"Interactive Debug Mode
def debug_breakpoint(data, context=""):
if os.environ.get('CLAUDE_DEBUG') == 'true':
print(f"🔍 Debug: {context}", file=sys.stderr)
print(f"Data: {json.dumps(data, indent=2)}", file=sys.stderr)
input("Press Enter to continue...")5.3 Session Recording and Replay
Record Sessions for Debugging
class SessionRecorder:
def record_event(self, event_type, data):
event = {
'timestamp': time.time(),
'type': event_type,
'data': data
}
self.current_session['events'].append(event)
def replay_session(self, session_id, speed=1.0):
# Replay events with timing5.4 VS Code Integration
Interactive Debugging Extension
- Enable LLMs to debug interactively
- Set breakpoints and inspect variables
- Step through AI-suggested fixes
- Available via MCP and VS Code Extension
6. Common Pitfalls and Solutions
6.1 Context Window Management
Problem: Context Overflow
- Long sessions fill context window
- Performance degradation
- AI loses track of earlier fixes
Solution:
# Manual compaction
/compact
# Clear between tasks
/clear
# Monitor context usage6.2 Permission and Configuration Issues
Problem: EACCES Errors
- npm permission issues
- Hook scripts not executable
- Directory write failures
Solution:
# Fix npm permissions
npm config set prefix ~/.npm-global
# Migrate Claude installation
claude migrate-installer
# Fix hook permissions
chmod +x .claude/hooks/*.sh6.3 Compilation and Testing Issues
Problem: Forgetting Build Steps
- Tests run without compilation
- Type errors not caught
- Stale build artifacts
Solution:
# Always in CLAUDE.md
"Before running tests:
1. Compile TypeScript: npm run build
2. Run linter: npm run lint
3. Type check: npm run typecheck"6.4 Cost Management
Problem: Unexpected High Costs
- Long-running sessions
- Inefficient token usage
- Wrong model selection
Solution:
- Monitor token usage in real-time
- Use appropriate models for tasks
- Implement token limits
- Track costs by project/user
7. Production Error Handling
7.1 Production-Ready Architecture
Error Handling Pipeline
- Capture: Comprehensive error capture
- Enrich: Add context and metadata
- Filter: Remove sensitive information
- Route: Send to appropriate systems
- Alert: Notify on critical issues
- Analyze: Post-mortem analysis
7.2 Security and Privacy
Data Sanitization
def sanitize_error_data(data):
# Remove API keys
data = re.sub(r'sk-ant-[\w-]+', '[REDACTED]', data)
# Remove emails
data = re.sub(r'[\w\.-]+@[\w\.-]+', '[EMAIL]', data)
return dataRetention Policies
- User feedback: 30 days
- Error logs: 90 days
- Metrics: 1 year
- No training on user data
7.3 Deployment Patterns
DevContainer Isolation
- Network restrictions for security
- Controlled environment
- Reproducible debugging
CI/CD Integration
# GitHub Actions
- name: Run with strict validation
run: |
export CLAUDE_STRICT_MODE=1
npm run build:strict7.4 Monitoring Stack
Complete Observability Solution
# Deploy monitoring stack
git clone https://github.com/ColeMurray/claude-code-otel
docker-compose up -d
# Configure Claude Code
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317Integration Options
- Datadog
- Prometheus + Grafana
- Loki for logs
- Custom dashboards
8. Best Practices Summary
8.1 Development Phase
- Start with console logging
- Use verbose/debug modes
- Implement comprehensive error handling
- Add context to all errors
- Test error scenarios
8.2 Testing Phase
- Write tests for error cases
- Use mock failures
- Test retry logic
- Verify error messages
- Check recovery paths
8.3 Production Phase
- Deploy full observability
- Set up alerts
- Monitor costs
- Track performance
- Regular audits
8.4 Team Practices
- Document error patterns
- Share debugging runbooks
- Conduct error reviews
- Update CLAUDE.md
- Train on tools
9. Advanced Patterns
9.1 Predictive Error Detection
- Analyze patterns in logs
- Predict failures before they occur
- Proactive remediation
- Anomaly detection
9.2 Self-Healing Systems
- Automatic error recovery
- Configuration rollback
- Service restart patterns
- Health check automation
9.3 Distributed Debugging
- Trace across multiple agents
- Correlate distributed logs
- Handle async operations
- Debug microservices
10. Resources and References
Official Documentation
Community Resources
Tools and Extensions
Conclusion
Effective error handling and debugging in Claude Code requires a multi-layered approach combining traditional debugging techniques with AI-specific strategies. By implementing comprehensive error handling, leveraging built-in tools, and maintaining proper observability, developers can build robust and reliable AI-assisted applications. The key is to start simple, gradually add sophistication, and continuously improve based on production experiences.