Error Handling
Comprehensive guide to error handling in the CognitiveX SDK.
Error Types
AUTHENTICATION_ERROR
Invalid or missing API key
Status: 401RATE_LIMIT_EXCEEDED
Too many requests in time window
Status: 429INVALID_REQUEST
Malformed request or missing required fields
Status: 400NOT_FOUND
Resource doesn't exist
Status: 404SERVER_ERROR
Internal server error
Status: 500Basic Error Handling
typescript
try {
const result = await client.memory.store({
content: "Your content"
});
} catch (error) {
if (error instanceof CognitiveXError) {
console.error('Error code:', error.code);
console.error('Message:', error.message);
console.error('Status:', error.statusCode);
}
}Handling Specific Errors
typescript
try {
const result = await client.cognition.reason({
query: "Your query"
});
} catch (error) {
if (error.code === 'AUTHENTICATION_ERROR') {
// Invalid API key
console.error('Please check your API key');
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
// Too many requests
console.error('Rate limit exceeded, retry after:', error.retryAfter);
} else if (error.code === 'INVALID_REQUEST') {
// Bad request
console.error('Invalid request:', error.details);
} else {
// Unknown error
console.error('Unexpected error:', error);
}
}Automatic Retry
Configure automatic retry for transient errors:
typescript
const client = new CognitiveXClient({
apiKey: process.env.COGNITIVEX_API_KEY,
retryStrategy: {
maxRetries: 3,
initialDelay: 1000,
maxDelay: 10000,
backoffMultiplier: 2,
retryableErrors: [
'RATE_LIMIT_EXCEEDED',
'SERVER_ERROR',
'NETWORK_ERROR'
]
}
});Custom Retry Logic
typescript
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
if (error.code === 'RATE_LIMIT_EXCEEDED') {
const delay = error.retryAfter || Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else if (error.code === 'AUTHENTICATION_ERROR') {
// Don't retry auth errors
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
// Usage
const result = await withRetry(() =>
client.memory.store({ content: "..." })
);Best Practices
- • Always wrap SDK calls in try-catch blocks
- • Handle specific error codes appropriately
- • Don't retry authentication errors
- • Implement exponential backoff for rate limits
- • Log errors for debugging
- • Provide user-friendly error messages
- • Monitor error rates in production
- • Set up alerts for high error rates