@ai-kod/errors
v0.7.1
Published
Centralized error handling system
Downloads
11
Readme
@ai-kod/errors
Centralized error handling system for AI-KOD orchestrator with hierarchical error classes, recovery strategies, and middleware integration.
Features
- Hierarchical Error Classes - structured error hierarchy for all types of errors
- Rich Context - detailed error information with correlationId, timestamp, and suggestions
- Recovery Strategies - retry with backoff, circuit breaker, graceful degradation
- Middleware Integration - direct integration with Hono framework
- Factory Methods - convenient methods for common error cases
- TypeScript Support - full type safety and IntelliSense support
Installation
pnpm add @ai-kod/errorsQuick Start
import {
ValidationError,
WorkflowError,
retryWithBackoff,
CircuitBreaker,
errorHandler,
correlationIdMiddleware
} from '@ai-kod/errors';
// Use factory methods for common errors
throw ValidationError.required('email');
throw WorkflowError.stageNotFound('workflow-123', 'missing-stage');
// Retry with exponential backoff
const result = await retryWithBackoff(
() => apiCall(),
{
maxAttempts: 3,
backoffStrategy: 'exponential',
shouldRetry: (error) => error.recoverable
}
);
// Circuit breaker for external services
const circuit = new CircuitBreaker(
() => externalService.call(),
{ failureThreshold: 5, timeoutMs: 30000 }
);
// Hono middleware integration
app.use('*', correlationIdMiddleware());
app.use('*', errorHandler);Error Classes
ValidationError
// Factory methods
ValidationError.required('fieldName');
ValidationError.invalidFormat('email', 'invalid@', 'valid email');
ValidationError.outOfRange('age', -5, 0, 150);WorkflowError
// Workflow-specific errors
WorkflowError.stageNotFound('workflow-id', 'stage-id');
WorkflowError.executionTimeout('workflow-id', 'stage-id', 30000);
WorkflowError.invalidStageTransition('workflow-id', 'from', 'to');RedisError
// Redis operation errors
RedisError.connectionFailed('redis://localhost:6379');
RedisError.operationTimeout('hget', 'key', 5000);
RedisError.keyNotFound('collection', 'key');NavigationError
// Navigation strategy errors
NavigationError.strategyNotFound('stage-id', ['linear', 'conditional']);
NavigationError.invalidChoice('stage-id', 'choice', ['yes', 'no']);ConfigurationError
// Configuration errors
ConfigurationError.missingRequired('API_KEY');
ConfigurationError.invalidValue('PORT', 'abc', 'number 1-65535');Recovery Strategies
Retry with Backoff
import { retryWithBackoff } from '@ai-kod/errors';
// Exponential backoff for external APIs
await retryWithBackoff(operation, {
maxAttempts: 3,
backoffStrategy: 'exponential',
initialDelayMs: 1000,
jitter: true,
shouldRetry: (error) => error.recoverable
});
// Linear backoff for internal services
await retryWithBackoff(operation, {
maxAttempts: 5,
backoffStrategy: 'linear',
initialDelayMs: 100
});Circuit Breaker
import { CircuitBreaker } from '@ai-kod/errors';
const circuit = new CircuitBreaker(operation, {
failureThreshold: 5,
timeoutMs: 30000,
recoveryTimeoutMs: 60000,
onStateChange: (state) => console.log(`Circuit: ${state}`)
});
try {
const result = await circuit.execute();
} catch (error) {
if (error.code === 'CIRCUIT_OPEN') {
// Handle circuit open with fallback
}
}Graceful Degradation
import { withGracefulDegradation } from '@ai-kod/errors';
const result = await withGracefulDegradation(
primaryOperation,
fallbackOperation,
{
timeout: 5000,
shouldFallback: (error) => error instanceof RedisError
}
);Middleware
Hono Integration
import { errorHandler, correlationIdMiddleware } from '@ai-kod/errors';
// Add to your Hono app
app.use('*', correlationIdMiddleware());
app.use('*', errorHandler);
// All errors will be automatically handled with:
// - Proper HTTP status codes
// - Correlation ID tracking
// - Structured error responses
// - Development vs production modesDocumentation
For detailed documentation, examples, and integration guides, see the AI-KOD Memory Bank.
License
MIT
