Debugging AI-Generated Code

Debugging Strategies with AI

4 min read

When AI-generated code doesn't work, how do you efficiently debug it? This lesson covers strategies for effective human-AI debugging collaboration.

The Debugging Decision Tree

Code doesn't work
├─ Do you understand what it should do?
│  ├─ No → Ask AI to explain the code first
│  └─ Yes → Continue
├─ Is there an error message?
│  ├─ Yes → Start with the error
│  └─ No → Add logging/debugging
├─ Is it a logic error or runtime error?
│  ├─ Logic → Trace through mentally or with debugger
│  └─ Runtime → Check inputs and error handling
└─ Can you isolate the problem?
   ├─ Yes → Fix the specific issue
   └─ No → Break into smaller parts

Strategy 1: The Error Message Approach

When you have an error, give AI everything:

I'm getting this error:

TypeError: Cannot read properties of undefined (reading 'name') at getUserName (src/utils/user.ts:15:23) at processUsers (src/services/process.ts:42:18)


Here's the relevant code:

```typescript
// src/utils/user.ts
export function getUserName(user: User): string {
  return user.profile.name;  // Line 15
}

The function is called with data from the API. What's causing this and how do I fix it?


**AI Response Quality Factors:**
- Full error message with stack trace
- Exact code causing the error
- Context about how/when it fails

## Strategy 2: The Minimal Reproduction

Isolate the bug to the smallest possible case:

This code fails silently:

async function fetchAndProcess() {
  const items = await fetchItems();
  const processed = items.map(processItem);
  return processed;
}

When I log items, I get the expected array. When I log processed, I get an array of Promises instead of values.

Why isn't this working?


**Why This Works:**
- Shows the exact problematic code
- Demonstrates what you've already verified
- Points to where the issue likely is

## Strategy 3: The Rubber Duck with AI

Explain your code to AI to find your own bugs:

I'm going to explain what this code should do. Tell me if you spot any issues.

This function should:

  1. Take a list of orders
  2. Group them by customer ID
  3. Calculate total spending per customer
  4. Return customers sorted by total spending

Here's my implementation:

[paste code]

Does my implementation match my description? Any edge cases I'm missing?


## Strategy 4: The Diff Debug

When code worked before and now doesn't:

This code was working yesterday. After my changes, it's broken.

Before (working):

[old code]

After (broken):

[new code]

The error is: [error message]

What did I break?


## Strategy 5: The Log-Based Debug

Add strategic logging and share with AI:

I added logging to debug this issue. Here's what I see:

Code:

async function processOrder(orderId: string) {
  console.log('1. Starting processOrder:', orderId);
  const order = await fetchOrder(orderId);
  console.log('2. Fetched order:', order);
  const validated = validateOrder(order);
  console.log('3. Validated:', validated);
  const result = await submitOrder(validated);
  console.log('4. Submitted:', result);
  return result;
}

Console output:

1. Starting processOrder: abc123
2. Fetched order: { id: 'abc123', items: [...] }
3. Validated: undefined

The log stops at step 3 with undefined. What's wrong with validateOrder?


## Strategy 6: The Test-Driven Debug

Write a failing test, then ask AI to fix:

This test should pass but doesn't:

describe('calculateDiscount', () => {
  it('should apply 20% discount for orders over $100', () => {
    const order = { subtotal: 150 };
    const result = calculateDiscount(order);
    expect(result.discount).toBe(30);
    expect(result.total).toBe(120);
  });
});

Test result:

Expected: 30
Received: 0

Here's the implementation:

[paste code]

Fix the implementation to pass this test.


## When to Debug Yourself vs Ask AI

### Debug Yourself When:
- Error message is clear
- Issue is in code you understand well
- Quick fix is obvious
- Learning opportunity

### Ask AI When:
- Error message is cryptic
- Unfamiliar library or pattern
- Multiple possible causes
- Already spent 15+ minutes stuck

## The Effective Bug Report Template

```markdown
## Problem
[One sentence describing what's wrong]

## Expected Behavior
[What should happen]

## Actual Behavior
[What actually happens]

## Error Message

[Full error with stack trace]


## Code
```typescript
[Relevant code, with line numbers if referencing specific lines]

What I've Tried

  • [Thing 1]
  • [Thing 2]

Environment

  • [Framework version]
  • [Node version]
  • [Browser if relevant]

## Iterative Debugging Conversation

### Round 1: Initial Report

User: [Bug report with all context] AI: [Analysis and first fix attempt]


### Round 2: Partial Fix

User: That fixed part of it, but now I see a different error: [new error] AI: [Analysis of new error and next fix]


### Round 3: Edge Case

User: Works now, but fails when input is empty. How do I handle that? AI: [Edge case handling]


### Round 4: Verification

User: Can you review the final code and confirm all cases are handled? AI: [Full review and confirmation]


## Anti-Patterns to Avoid

### Don't: Vague Problem Description

❌ "It doesn't work" ✅ "The function returns undefined instead of the user object when the API call succeeds"


### Don't: Missing Context

❌ "Fix this error: undefined is not a function" ✅ "Fix this error: undefined is not a function [+ stack trace + code + what triggers it]"


### Don't: Not Reading the Error

❌ "I don't understand this error, fix it" ✅ "This error says X. I think it means Y. Is that right? How do I fix it?"


### Don't: Changing Too Much at Once

❌ "I rewrote the whole function and now it's broken" ✅ "I changed line 15 from X to Y and now this error occurs"


## Pro Tips

### 1. Preserve the Error
Copy the full error before trying to fix it.

### 2. Git Stash Before Debug
```bash
git stash  # Save current changes
# Debug
git stash pop  # Restore after

3. Use Debugger Statements

function problematicFunction(data) {
  debugger;  // Pause here in browser DevTools
  // ...
}

4. Binary Search Large Files

If a large file has issues, comment out half and see if the error persists.

Debugging Truth: The quality of AI debugging help is directly proportional to the quality of information you provide. Be specific, be complete, be systematic.

You now know how to debug AI-generated code effectively. In Module 6, we'll learn project workflows and best practices for vibe coding at scale. :::

Quiz

Module 5: Debugging AI-Generated Code

Take Quiz