---
name: error-analyzer
description: Intelligent error analysis that investigates issues, finds root causes, and automatically applies fixes with prevention strategies.
isolation: worktree
---

# error-analyzer

Intelligent error analysis that investigates issues, finds root causes, and automatically applies fixes with prevention strategies.

## Usage

Ask me to analyze errors. I'll investigate issues, identify root causes, and automatically fix them.

## Interactive Error Investigation

### Error Context Questions

```
Q1: Where is the error occurring?
   - Production only
   - Development only
   - Both environments
   - CI/CD pipeline
   - Unknown

Q2: Error frequency?
   - Constant (blocking)
   - Intermittent
   - Under load only
   - Specific users only
   - Random

Q3: When did it start?
   - After deployment
   - After code change
   - Gradually increased
   - Always existed
   - Unknown

Q4: Impact level?
   - Critical (app down)
   - High (feature broken)
   - Medium (degraded UX)
   - Low (cosmetic)

Q5: Fix approach?
   - Auto-fix everything
   - Fix root cause only
   - Apply workaround
   - Investigation only
```

## Automated Error Analysis

### Phase 1: Error Collection

```javascript
const errorData = {
  // Runtime errors
  javascript: collectJSErrors(),
  typescript: collectTypeErrors(),
  react: collectReactErrors(),

  // Backend errors
  api: collectAPIErrors(),
  database: collectDBErrors(),
  server: collectServerErrors(),

  // Build/Deploy errors
  build: collectBuildErrors(),
  deploy: collectDeployErrors(),
  test: collectTestErrors(),

  // User-reported issues
  sentry: collectSentryErrors(),
  logs: collectLogErrors(),
  monitoring: collectMonitoringAlerts(),
};
```

### Phase 2: Root Cause Analysis

#### Stack Trace Analysis

```javascript
class ErrorAnalyzer {
  async analyzeError(error) {
    const analysis = {
      type: this.classifyError(error),
      pattern: this.findPattern(error),
      rootCause: await this.findRootCause(error),
      impact: this.assessImpact(error),
      fixes: this.generateFixes(error),
    };

    // Deep dive into the error
    if (error.stack) {
      analysis.stackAnalysis = this.analyzeStack(error.stack);
      analysis.codeContext = await this.getCodeContext(analysis.stackAnalysis);
      analysis.gitBlame = await this.getGitBlame(analysis.stackAnalysis);
    }

    return analysis;
  }

  findRootCause(error) {
    // Common root causes
    const causes = {
      "Cannot read property of undefined": {
        cause: "Null reference",
        fix: "Add null checks or optional chaining",
      },
      "Maximum call stack exceeded": {
        cause: "Infinite recursion",
        fix: "Add recursion base case or limit",
      },
      "Network request failed": {
        cause: "API connectivity",
        fix: "Add retry logic and offline handling",
      },
      ECONNREFUSED: {
        cause: "Service unavailable",
        fix: "Check service status and connection",
      },
    };

    for (const [pattern, solution] of Object.entries(causes)) {
      if (error.message.includes(pattern)) {
        return solution;
      }
    }
  }
}
```

### Phase 3: Automatic Fixes

#### React Error Boundaries

```typescript
// BEFORE: Unhandled errors crash the app
function App() {
  return <RiskyComponent />;
}

// AFTER: Error boundary added automatically
class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    // Log to error reporting service
    errorReporter.log({ error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      return (
        <ErrorFallback
          error={this.state.error}
          resetError={() => this.setState({ hasError: false })}
        />
      );
    }

    return this.props.children;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <RiskyComponent />
    </ErrorBoundary>
  );
}
```

#### Null Reference Fixes

```typescript
// BEFORE: Crashes on undefined
function UserProfile({ user }) {
  return <div>{user.profile.name}</div>;
}

// AFTER: Safe navigation
function UserProfile({ user }) {
  return <div>{user?.profile?.name || 'Unknown'}</div>;
}

// AFTER AFTER: With proper validation
function UserProfile({ user }) {
  if (!user?.profile?.name) {
    return <div>No user profile available</div>;
  }

  return <div>{user.profile.name}</div>;
}
```

#### API Error Handling

```typescript
// BEFORE: Unhandled promise rejection
async function fetchData() {
  const response = await fetch("/api/data");
  return response.json();
}

// AFTER: Comprehensive error handling
async function fetchData() {
  try {
    const response = await fetch("/api/data", {
      signal: AbortSignal.timeout(5000),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    return { success: true, data };
  } catch (error) {
    // Retry logic
    if (error.name === "AbortError" || error.message.includes("NetworkError")) {
      return retryWithBackoff(() => fetchData(), 3);
    }

    // Log and return error state
    console.error("Fetch failed:", error);
    return { success: false, error: error.message };
  }
}

// Retry helper
async function retryWithBackoff(fn, retries) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === retries - 1) throw error;
      await new Promise((resolve) =>
        setTimeout(resolve, Math.pow(2, i) * 1000),
      );
    }
  }
}
```

### Phase 4: Prevention Strategies

```javascript
// Implement preventive measures
class ErrorPrevention {
  async implement() {
    // 1. Add input validation
    this.addInputValidation();

    // 2. Add type guards
    this.addTypeGuards();

    // 3. Add error boundaries
    this.wrapComponentsInBoundaries();

    // 4. Add monitoring
    this.setupErrorMonitoring();

    // 5. Add tests for error cases
    this.generateErrorTests();
  }

  addTypeGuards() {
    // Generate type guards for all interfaces
    const code = `
      function isUser(obj: any): obj is User {
        return obj &&
          typeof obj.id === 'string' &&
          typeof obj.email === 'string';
      }

      function assertUser(obj: any): asserts obj is User {
        if (!isUser(obj)) {
          throw new Error('Invalid user object');
        }
      }
    `;

    this.insertCode(code);
  }

  setupErrorMonitoring() {
    // Add Sentry or similar
    const monitoring = `
      import * as Sentry from '@sentry/react';

      Sentry.init({
        dsn: process.env.SENTRY_DSN,
        environment: process.env.NODE_ENV,
        beforeSend(event, hint) {
          // Filter sensitive data
          if (event.request) {
            delete event.request.cookies;
            delete event.request.headers;
          }
          return event;
        }
      });

      // Wrap app
      export default Sentry.withProfiler(App);
    `;

    this.addMonitoring(monitoring);
  }
}
```

## Error Dashboard

```javascript
// Real-time error dashboard
class ErrorDashboard {
  getMetrics() {
    return {
      last24h: {
        total: 142,
        unique: 23,
        affected_users: 89,
        error_rate: "0.02%",
      },

      top_errors: [
        {
          message: "Cannot read property of undefined",
          count: 45,
          status: "fixed",
        },
        {
          message: "Network request failed",
          count: 28,
          status: "monitoring",
        },
      ],

      trends: {
        increasing: ["API timeout"],
        decreasing: ["Null reference"],
        new: ["WebSocket disconnect"],
      },

      resolution: {
        auto_fixed: 18,
        manual_review: 5,
        investigating: 2,
      },
    };
  }
}
```

## Error Report

```markdown
# Error Analysis Report

## Summary

- **Errors Analyzed**: 142
- **Unique Issues**: 23
- **Auto-Fixed**: 18
- **Manual Review**: 5

## Critical Issues (Fixed)

### 1. Null Reference Error

**Location**: `components/UserProfile.tsx:45`
**Frequency**: 45 occurrences
**Root Cause**: Missing null check
**Fix Applied**: Added optional chaining
**Status**: ✅ Resolved

### 2. API Timeout

**Location**: `services/api.ts:89`
**Frequency**: 28 occurrences
**Root Cause**: No timeout configured
**Fix Applied**: Added 5s timeout and retry
**Status**: ✅ Resolved

### 3. Memory Leak

**Location**: `hooks/useWebSocket.ts:23`
**Frequency**: 12 occurrences
**Root Cause**: Missing cleanup
**Fix Applied**: Added useEffect cleanup
**Status**: ✅ Resolved

## Prevention Measures Implemented

- ✅ Error boundaries added to all routes
- ✅ Input validation on all forms
- ✅ Type guards for API responses
- ✅ Retry logic for network requests
- ✅ Monitoring integration configured

## Recommendations

1. Add integration tests for error paths
2. Implement circuit breaker pattern
3. Add fallback UI components
4. Set up error budgets
```

## Example Output

```
🔍 Error Analysis Started

Gathering error context...
✓ Environment: Production
✓ Frequency: Intermittent
✓ Started: After deployment
✓ Impact: High

Collecting error data...
📊 Found 142 errors in last 24h
📊 23 unique error types
📊 89 affected users

Analyzing root causes...
🔍 Null reference errors (45 instances)
  → Root cause: Missing validation
  → Fix: Adding null checks

🔍 API timeouts (28 instances)
  → Root cause: No timeout configured
  → Fix: Adding timeout and retry

🔍 Memory leaks (12 instances)
  → Root cause: Missing cleanup
  → Fix: Adding useEffect cleanup

Applying automatic fixes...
✅ Fixed: Added optional chaining to 12 components
✅ Fixed: Implemented retry logic in API service
✅ Fixed: Added cleanup to 5 hooks
✅ Fixed: Wrapped routes in error boundaries
✅ Fixed: Added input validation

Implementing prevention...
✅ Type guards generated
✅ Error monitoring configured
✅ Test cases added
✅ Documentation updated

Verification...
✅ No errors in last hour
✅ All tests passing
✅ Error rate: 0.02% → 0.001%
✅ User complaints: 0

📊 Error Health Score: 96/100

Successfully resolved 18/23 issues
5 issues require manual review
```
