Foundations

Debugging with AI Assistance

Lesson 1 of 4 Estimated Time 50 min

Debugging with AI Assistance

Debugging is frustrating. You have a symptom (the code isn’t working), but the cause isn’t obvious. Traditional debugging involves hypothesis testing: change something, re-run, check if it helped. With AI assistance, you can compress this cycle significantly by leveraging an expert’s pattern recognition.

How AI Helps With Debugging

Instead of you coming up with hypotheses, the AI can see patterns and suggest multiple possibilities at once.

Traditional debugging:

1. See error
2. Guess cause ("maybe it's null?")
3. Add logging
4. Re-run
5. Guess again
[repeat many times]

AI-assisted debugging:

1. Paste error + code to AI
2. AI says "This looks like three things could cause it: X, Y, Z"
3. You test the most likely
4. Solved in one or two iterations instead of ten

The AI isn’t solving the problem for you — it’s helping you solve it faster.

Sharing Errors Effectively

The key to getting good AI debugging help is sharing the error context completely.

Information to Always Include

1. Full stack trace or error message

Bad:

"I'm getting an error"

Good:

TypeError: Cannot read property 'email' of undefined
  at getUserEmail (src/services/user.js:12:3)
  at processOrder (src/handlers/order.js:24:8)
[full stack trace]

2. What you expected to happen

"I expected getUserEmail() to return the user's email address.
Instead it's throwing 'Cannot read property 'email' of undefined'"

3. What code triggered the error

"The error happens when I call processOrder with an order ID.
Here's the code:
[paste relevant code]"

4. When it started happening

"This worked yesterday. Started failing after I refactored
getUserEmail() to accept an options parameter."

Complete Debugging Request Template

Error Message:
[full error + stack trace]

What I Expected:
[what should happen]

What Actually Happened:
[error behavior]

Relevant Code:
[functions involved in the error]

Environment:
- Node.js 18.10
- Database: PostgreSQL
- Framework: Express

What I've Already Tried:
- Checked that user exists (it does)
- Added logging to confirm email field (exists in DB)
- Restarted the server

What Changed Recently:
- Refactored getUserEmail() yesterday

With this information, the AI can quickly narrow down the issue.

Common Debugging Patterns

Pattern 1: The Null/Undefined Error

Error:

TypeError: Cannot read property 'x' of undefined

Ask:

"I'm getting this error: [error]
Here's the code: [code]

The object is defined earlier in the function.
Why would it be undefined here?"

What the AI checks:

  • Is the object being reassigned to undefined?
  • Is there a code path that doesn’t set it?
  • Is it being deleted?
  • Is it coming from an API that returned null?

Example:

// Bug: orders might be null from API
const orders = await api.getOrders();
const firstOrder = orders[0]; // Error if orders is null!

// AI suggests:
const orders = await api.getOrders() || [];
const firstOrder = orders[0];

Pattern 2: The Race Condition

Error: Intermittent failures that don’t reproduce consistently.

Ask:

"This error happens randomly, about 10% of the time.
Here's the code: [async code]

What could cause intermittent failures?"

What the AI checks:

  • Are async operations not being awaited?
  • Are race conditions between parallel requests?
  • Is timing-dependent logic involved?

Example:

// Bug: Race condition
function updateUser(id, data) {
  const user = db.findUser(id);
  user.name = data.name;
  db.save(user); // Not awaited!
  return user;
}

// AI suggests:
async function updateUser(id, data) {
  const user = await db.findUser(id);
  user.name = data.name;
  await db.save(user); // Await the save
  return user;
}

Pattern 3: The Type Mismatch

Error:

TypeError: user.age.toFixed is not a function

Ask:

"I'm getting 'toFixed is not a function' on user.age.
User should have age as a number.
Code: [code]"

What the AI checks:

  • Is the type coming from the wrong place?
  • Could the API be returning a string instead of number?
  • Is there a JSON serialization issue?

Example:

// Bug: age is string from JSON
const user = JSON.parse(response);
console.log(user.age.toFixed(2)); // Error if age is "25"

// AI suggests:
const user = JSON.parse(response);
const age = parseInt(user.age, 10);
console.log(age.toFixed(2));

Pattern 4: The Logic Error

Error: Code runs without errors but produces wrong results.

Ask:

"This discount calculation is giving wrong results.
Input: price = 100, discount = 10
Expected output: 90
Actual output: 100

Code: [discount function]"

What the AI checks:

  • Is the math correct?
  • Is the condition right?
  • Is there operator precedence issue?

Example:

# Bug: Wrong operator precedence
discount = price * 0.1 + 5  # Applies 10% THEN adds 5
# Should be:
discount = price * (0.1 + 0.05)  # Applies 15% total

Rubber Duck Debugging with AI

“Rubber ducking” is explaining code line-by-line to find bugs. AI is an excellent rubber duck:

You: "Walk me through what this code does, line by line:
[paste function]"

AI: "Line 1: Get user by ID
    Line 2: Check if user exists
    Line 3: Get user's orders
    [continues...]

    Wait — line 10 deletes the user from cache
    but line 11 tries to use the user.
    That's the bug!"

You’re explaining to clarify for yourself, but the AI spots issues while explaining.

Systematic Bug Hunting

When you have no idea what’s wrong:

Step 1: Isolate the Problem
"The entire checkout process fails. Let me test parts:
- API endpoint: works
- Database query: works
- Tax calculation: works
- Payment processing: FAILS HERE"

Step 2: Share the Isolated Part
"Only payment processing is broken. Here's the code:
[paste payment code only, not the whole system]"

Step 3: Get Focused Help
"Why is this payment code failing?
Input: [example input]
Expected: [expected output]
Actual: [actual output]"

AI now has a much smaller scope to analyze.

Error Analysis Workflow

Workflow: The Infuriating Error

You get an error that makes no sense:

You: "This error doesn't make sense. Here's what's happening:
     1. I'm calling saveUser(user)
     2. user object has all required fields
     3. Database schema allows these fields
     4. Error: 'Column name not found'

     Code: [code]"

AI: "The error might be... let me look at:
    - How you're constructing the query
    - If you're using the right table name
    - If there's a typo in the column name

    Ah! I see it. You're using 'usrName' here
    but the database has 'userName'. Column name typo."

Workflow: The Missing Validation

You: "My API request keeps failing validation,
     but the data looks correct to me.

     Here's what I'm sending: [data]
     Here's the validation schema: [schema]
     Error: [error]"

AI: "Looking at your schema, it requires...
    You're sending [field], but not [other required field].
    The schema expects [format], but you're sending [different format].
    That's why validation fails."

AI for Understanding Legacy Code Errors

When working with unfamiliar code:

You: "This legacy code is throwing an error I don't understand.
     Error: [error]
     Code: [unfamiliar code]
     Context: This is a 10-year-old payment system"

AI: "This code is using [old pattern].
    The error happens because [explains the legacy way].
    In modern code, we'd do [modern approach].
    But to fix this quickly: [minimal fix for legacy code]"

The AI understands both old and new patterns and can bridge them.

Common Debugging Mistakes

Mistake 1: Not Sharing Enough Context

Bad: "Why is this failing?"
     [shows 3 lines of code with no context]

Good: "Here's what the code does...
      Here's what should happen...
      Here's the error...
      Here's the relevant code..."

More context = better debugging.

Mistake 2: Assuming the AI Knows Your Codebase

Bad: "The getUserPermissions function is broken"
     [AI has no idea what that function does]

Good: "The getUserPermissions function is broken.
      Here it is: [paste function]"

Always paste the relevant code.

Mistake 3: Sharing Too Much Unrelated Code

Bad: [Paste 500 lines of code]
     "One of these is broken"

Good: "I've narrowed it down to these 20 lines: [paste]
      All the code around it works fine"

Narrow down before asking for help.

Mistake 4: Not Describing What You’ve Tried

Bad: "This doesn't work"

Good: "This doesn't work. I've tried:
      - Checking that the input is valid (it is)
      - Logging intermediate values (logging shows X)
      - Restarting the server (didn't help)
      So the issue is likely in the calculation itself"

What you’ve tried eliminates possibilities.

Performance Debugging

Sometimes “bugs” are performance issues.

You: "This query is slow. It takes 5 seconds for 1,000 rows.
     Here's the query: [SQL]
     Here's the schema: [schema]"

AI: "I see three issues:
    1. Missing index on the join column
    2. Loading more data than needed
    3. No result limit

    Here's the optimized version: [optimized SQL]"

The same debugging approach works for performance.

Real-World Debugging Example

Error: "TypeError: user.profile.avatar.url is not defined"

Code:
function getAvatarUrl(userId) {
  const user = db.query('SELECT * FROM users WHERE id = ?', userId);
  return user.profile.avatar.url;
}

What you tried:
- Confirmed users have profiles in database
- Logged user object (profile field exists)
- Still throws error

Ask AI:
"Why would user.profile exist but user.profile.avatar be undefined?"

AI identifies:
- user.profile might be a string (JSON), not object
- Need to parse JSON
- Or avatar might be missing entirely

Solution:
function getAvatarUrl(userId) {
  const user = db.query('SELECT * FROM users WHERE id = ?', userId);
  const profile = typeof user.profile === 'string'
    ? JSON.parse(user.profile)
    : user.profile;
  return profile?.avatar?.url || null;
}

Exercises

  1. Stack Trace Analysis: Find a recent error in your code. Share with AI:

    • Full stack trace
    • Relevant code
    • What you expected Ask for analysis. How close was AI to the cause?
  2. Systematic Isolation: Find a failing feature. Try to isolate which part fails:

    • Test each sub-component
    • Narrow down to the broken function
    • Ask AI for help on just that function Note how isolation made the problem clearer.
  3. Debugging Session: Use AI to debug three real errors from your project:

    • Document each error
    • What caused it (after debugging)
    • How AI helped identify it
    • What you’ll do differently next time
  4. Rubber Duck Session: Pick a complex function. Ask AI to:

    • Explain what it does line-by-line
    • Identify any issues
    • Suggest improvements Compare this to debugging without AI.