forked from ruvnet/ruflo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-api-error-handling.ts
More file actions
131 lines (112 loc) · 4.17 KB
/
claude-api-error-handling.ts
File metadata and controls
131 lines (112 loc) · 4.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/env tsx
/**
* Example demonstrating enhanced Claude API error handling
* Shows how to handle various error scenarios gracefully
*/
import { ClaudeAPIClient } from '../src/api/claude-client.js';
import {
ClaudeAPIError,
ClaudeInternalServerError,
ClaudeRateLimitError,
ClaudeNetworkError,
getUserFriendlyError,
} from '../src/api/claude-api-errors.js';
import { ConsoleLogger } from '../src/core/logger.js';
import { ConfigManager } from '../src/config/config-manager.js';
async function main() {
const logger = new ConsoleLogger();
const configManager = ConfigManager.getInstance();
// Initialize the Claude client with enhanced error handling
const client = new ClaudeAPIClient(logger, configManager, {
enableHealthCheck: true,
healthCheckInterval: 300000, // 5 minutes
retryAttempts: 3,
retryDelay: 1000,
retryJitter: true,
});
console.log('🚀 Claude API Enhanced Error Handling Demo\n');
// Example 1: Check API health
console.log('1️⃣ Checking API health...');
const health = await client.performHealthCheck();
console.log(`Health status: ${health.healthy ? '✅ Healthy' : '❌ Unhealthy'}`);
if (health.latency) {
console.log(`Latency: ${health.latency}ms`);
}
console.log();
// Example 2: Handle various error scenarios
console.log('2️⃣ Demonstrating error handling...\n');
try {
// This will work if you have a valid API key
const response = await client.sendMessage([
{ role: 'user', content: 'Hello! Can you briefly explain error handling?' }
]);
console.log('✅ Success! Response:', response.content[0].text);
} catch (error) {
handleError(error);
}
// Example 3: Simulate different error scenarios
console.log('\n3️⃣ Error scenarios and user-friendly messages:\n');
// Simulate various errors
const errorScenarios = [
new ClaudeInternalServerError('Simulated server error'),
new ClaudeRateLimitError('Simulated rate limit', 60),
new ClaudeNetworkError('Simulated network error'),
];
for (const error of errorScenarios) {
console.log(`--- ${error.name} ---`);
const errorInfo = getUserFriendlyError(error);
console.log(`Title: ${errorInfo.title}`);
console.log(`Message: ${errorInfo.message}`);
console.log(`Retryable: ${errorInfo.retryable ? 'Yes' : 'No'}`);
console.log('Suggestions:');
errorInfo.suggestions.forEach((suggestion, i) => {
console.log(` ${i + 1}. ${suggestion}`);
});
console.log();
}
// Example 4: Listen to error events
console.log('4️⃣ Setting up error event listeners...\n');
client.on('error', ({ error, userFriendly }) => {
console.log('🔔 Error event received:');
console.log(` Error: ${error.message}`);
console.log(` User-friendly title: ${userFriendly.title}`);
console.log(` Retryable: ${userFriendly.retryable}`);
});
client.on('health_check', (result) => {
console.log('🔔 Health check event:', {
healthy: result.healthy,
latency: result.latency,
timestamp: result.timestamp,
});
});
// Example 5: Circuit breaker behavior
console.log('\n5️⃣ Circuit breaker protection:\n');
console.log('If multiple consecutive failures occur, the circuit breaker');
console.log('will temporarily prevent new requests to protect the system.');
console.log('This prevents cascading failures and gives the API time to recover.\n');
// Clean up
client.destroy();
console.log('✨ Demo completed!');
}
function handleError(error: unknown) {
if (error instanceof ClaudeAPIError) {
const errorInfo = getUserFriendlyError(error);
console.log(`\n❌ Error: ${errorInfo.title}`);
console.log(`Message: ${errorInfo.message}`);
console.log(`Status Code: ${error.statusCode || 'N/A'}`);
console.log(`Retryable: ${error.retryable ? 'Yes' : 'No'}`);
if (errorInfo.suggestions.length > 0) {
console.log('\n💡 Suggestions:');
errorInfo.suggestions.forEach((suggestion, i) => {
console.log(` ${i + 1}. ${suggestion}`);
});
}
} else {
console.error('Unexpected error:', error);
}
}
// Run the demo
main().catch((error) => {
console.error('Demo failed:', error);
process.exit(1);
});