**Callsign:** Sentinel
Creates robust error handling systems with typed errors, retry logic, and circuit breakers.
/plugin marketplace add Lobbi-Docs/claude/plugin install api-integration-helper@claude-orchestrationCallsign: Sentinel Model: Sonnet Specialization: Robust error handling with typed errors and resilience patterns
Creates comprehensive error handling systems with typed error classes, retry logic, circuit breakers, timeouts, and error recovery strategies.
Error Analysis
Error Class Generation
Resilience Patterns
Error Reporting
export class APIError extends Error {
constructor(
message: string,
public readonly statusCode?: number,
public readonly code?: string,
public readonly details?: unknown,
public readonly requestId?: string
) {
super(message);
this.name = 'APIError';
Object.setPrototypeOf(this, APIError.prototype);
}
toJSON() {
return {
name: this.name,
message: this.message,
statusCode: this.statusCode,
code: this.code,
details: this.details,
requestId: this.requestId,
timestamp: new Date().toISOString(),
};
}
}
export class AuthenticationError extends APIError {
constructor(message: string, details?: unknown) {
super(message, 401, 'AUTHENTICATION_ERROR', details);
this.name = 'AuthenticationError';
}
}
export class AuthorizationError extends APIError {
constructor(message: string, details?: unknown) {
super(message, 403, 'AUTHORIZATION_ERROR', details);
this.name = 'AuthorizationError';
}
}
export class RateLimitError extends APIError {
constructor(
message: string,
public readonly retryAfter: number,
details?: unknown
) {
super(message, 429, 'RATE_LIMIT_ERROR', details);
this.name = 'RateLimitError';
}
}
export class ValidationError extends APIError {
constructor(
message: string,
public readonly errors: ValidationErrorDetail[]
) {
super(message, 400, 'VALIDATION_ERROR', { errors });
this.name = 'ValidationError';
}
}
export class NetworkError extends APIError {
constructor(message: string, public readonly cause: Error) {
super(message, undefined, 'NETWORK_ERROR', { cause: cause.message });
this.name = 'NetworkError';
}
}
export class TimeoutError extends APIError {
constructor(message: string, public readonly timeoutMs: number) {
super(message, 408, 'TIMEOUT_ERROR', { timeoutMs });
this.name = 'TimeoutError';
}
}
export interface RetryConfig {
maxRetries: number;
initialDelayMs: number;
maxDelayMs: number;
backoffMultiplier: number;
retryableStatuses: number[];
retryableErrors: string[];
}
export class RetryHandler {
constructor(private config: RetryConfig) {}
async execute<T>(
fn: () => Promise<T>,
context?: string
): Promise<T> {
let lastError: Error | undefined;
let delay = this.config.initialDelayMs;
for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error as Error;
// Don't retry if not retryable
if (!this.isRetryable(error)) {
throw error;
}
// Don't retry if max attempts reached
if (attempt === this.config.maxRetries) {
throw new APIError(
`Max retries (${this.config.maxRetries}) exceeded`,
undefined,
'MAX_RETRIES_EXCEEDED',
{ lastError, context }
);
}
// Log retry attempt
console.warn(
`Retry attempt ${attempt + 1}/${this.config.maxRetries} after ${delay}ms`,
{ error, context }
);
// Wait before retry
await this.sleep(delay);
// Exponential backoff
delay = Math.min(
delay * this.config.backoffMultiplier,
this.config.maxDelayMs
);
}
}
throw lastError;
}
private isRetryable(error: unknown): boolean {
if (error instanceof APIError) {
// Retry on specific status codes
if (error.statusCode && this.config.retryableStatuses.includes(error.statusCode)) {
return true;
}
// Retry on specific error codes
if (error.code && this.config.retryableErrors.includes(error.code)) {
return true;
}
}
// Retry on network errors
if (error instanceof NetworkError || error instanceof TimeoutError) {
return true;
}
return false;
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
export interface CircuitBreakerConfig {
threshold: number; // Number of failures before opening
timeout: number; // Time to wait before half-open
monitoringPeriod: number; // Time window for counting failures
}
export enum CircuitState {
CLOSED = 'CLOSED',
OPEN = 'OPEN',
HALF_OPEN = 'HALF_OPEN',
}
export class CircuitBreaker {
private state: CircuitState = CircuitState.CLOSED;
private failures: number[] = [];
private lastFailureTime?: number;
private successCount = 0;
constructor(private config: CircuitBreakerConfig) {}
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === CircuitState.OPEN) {
if (this.shouldAttemptReset()) {
this.state = CircuitState.HALF_OPEN;
this.successCount = 0;
} else {
throw new APIError(
'Circuit breaker is OPEN',
503,
'CIRCUIT_BREAKER_OPEN',
{
resetAt: this.lastFailureTime! + this.config.timeout,
}
);
}
}
try {
const result = await fn();
// Success in HALF_OPEN state
if (this.state === CircuitState.HALF_OPEN) {
this.successCount++;
if (this.successCount >= 3) {
this.reset();
}
}
return result;
} catch (error) {
this.recordFailure();
throw error;
}
}
private recordFailure(): void {
const now = Date.now();
this.lastFailureTime = now;
// Add failure timestamp
this.failures.push(now);
// Remove old failures outside monitoring period
this.failures = this.failures.filter(
timestamp => now - timestamp < this.config.monitoringPeriod
);
// Open circuit if threshold exceeded
if (this.failures.length >= this.config.threshold) {
this.state = CircuitState.OPEN;
console.error('Circuit breaker OPENED', {
failures: this.failures.length,
threshold: this.config.threshold,
});
}
}
private shouldAttemptReset(): boolean {
if (!this.lastFailureTime) return false;
return Date.now() - this.lastFailureTime >= this.config.timeout;
}
private reset(): void {
this.state = CircuitState.CLOSED;
this.failures = [];
this.lastFailureTime = undefined;
this.successCount = 0;
console.info('Circuit breaker CLOSED');
}
getState(): CircuitState {
return this.state;
}
}
export function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
message?: string
): Promise<T> {
return Promise.race([
promise,
new Promise<never>((_, reject) =>
setTimeout(
() => reject(new TimeoutError(
message || `Operation timed out after ${timeoutMs}ms`,
timeoutMs
)),
timeoutMs
)
),
]);
}
You are an expert code simplification specialist focused on enhancing code clarity, consistency, and maintainability while preserving exact functionality. Your expertise lies in applying project-specific best practices to simplify and improve code without altering its behavior. You prioritize readable, explicit code over overly compact solutions. This is a balance that you have mastered as a result your years as an expert software engineer.
Use this agent when you need to review code for adherence to project guidelines, style guides, and best practices. This agent should be used proactively after writing or modifying code, especially before committing changes or creating pull requests. It will check for style violations, potential issues, and ensure code follows the established patterns in CLAUDE.md. Also the agent needs to know which files to focus on for the review. In most cases this will recently completed work which is unstaged in git (can be retrieved by doing a git diff). However there can be cases where this is different, make sure to specify this as the agent input when calling the agent. Examples: <example> Context: The user has just implemented a new feature with several TypeScript files. user: "I've added the new authentication feature. Can you check if everything looks good?" assistant: "I'll use the Task tool to launch the code-reviewer agent to review your recent changes." <commentary> Since the user has completed a feature and wants validation, use the code-reviewer agent to ensure the code meets project standards. </commentary> </example> <example> Context: The assistant has just written a new utility function. user: "Please create a function to validate email addresses" assistant: "Here's the email validation function:" <function call omitted for brevity> assistant: "Now I'll use the Task tool to launch the code-reviewer agent to review this implementation." <commentary> Proactively use the code-reviewer agent after writing new code to catch issues early. </commentary> </example> <example> Context: The user is about to create a PR. user: "I think I'm ready to create a PR for this feature" assistant: "Before creating the PR, I'll use the Task tool to launch the code-reviewer agent to ensure all code meets our standards." <commentary> Proactively review code before PR creation to avoid review comments and iterations. </commentary> </example>
Use this agent when you need to analyze code comments for accuracy, completeness, and long-term maintainability. This includes: (1) After generating large documentation comments or docstrings, (2) Before finalizing a pull request that adds or modifies comments, (3) When reviewing existing comments for potential technical debt or comment rot, (4) When you need to verify that comments accurately reflect the code they describe. <example> Context: The user is working on a pull request that adds several documentation comments to functions. user: "I've added documentation to these functions. Can you check if the comments are accurate?" assistant: "I'll use the comment-analyzer agent to thoroughly review all the comments in this pull request for accuracy and completeness." <commentary> Since the user has added documentation comments and wants them checked, use the comment-analyzer agent to verify their accuracy against the actual code. </commentary> </example> <example> Context: The user just asked to generate comprehensive documentation for a complex function. user: "Add detailed documentation for this authentication handler function" assistant: "I've added the documentation. Now let me use the comment-analyzer agent to verify that the comments are accurate and helpful for long-term maintenance." <commentary> After generating large documentation comments, proactively use the comment-analyzer to ensure quality. </commentary> </example> <example> Context: The user is preparing to create a pull request with multiple code changes and comments. user: "I think we're ready to create the PR now" assistant: "Before creating the pull request, let me use the comment-analyzer agent to review all the comments we've added or modified to ensure they're accurate and won't create technical debt." <commentary> Before finalizing a PR, use the comment-analyzer to review all comment changes. </commentary> </example>