AI for Coding11 min read

Debugging with AI

From cryptic error messages to instant fixes
scope:Applied AIdifficulty:Beginner

It's 2 AM and Your Code Is Broken

It's 2 AM. You've been staring at the screen for hours. Your code doesn't work. The error message says something like:

TypeError: Cannot read properties of undefined (reading 'map')

It might as well be written in ancient Egyptian. Before AI, here's what you'd do: copy the error, open Stack Overflow, scroll through 47 answers from 2014 (half of which are "have you tried turning it off and on again?"), find one that almost works, try it, get a different error, and repeat until sunrise.

Now? You paste the error into an AI. In seconds, it tells you: "Your users variable is undefined because the API call hasn't finished yet. You're trying to .map() over data that doesn't exist yet. Here's the fix..."

Welcome to debugging with AI β€” and it's a game-changer.

The AI Debugging Workflow

Debugging with AI follows a simple but powerful pattern:

  • Step 1: Paste the error β€” Copy the full error message and stack trace. Don't paraphrase. Give the AI the raw text.
  • Step 2: Provide context β€” Share the relevant code. The function that's failing, the file it's in, what you were trying to do.
  • Step 3: Get the explanation β€” The AI explains why the error happened in plain English. Not just "what's wrong" but why it's wrong.
  • Step 4: Get the fix β€” The AI suggests a specific code change. Often it rewrites the broken code with the fix highlighted.
  • Step 5: Understand and verify β€” Read the explanation. Make sure the fix makes sense. Then apply it and test.

The key insight: AI doesn't just fix bugs β€” it teaches you why the bug exists. Over time, you start recognizing patterns and catching bugs before they happen.

How to Give AI Enough Context

The #1 mistake people make when debugging with AI is not giving enough context. Saying "my code doesn't work" is like calling a mechanic and saying "my car is broken" β€” they need to see the car.

Here's what to include:

  • The full error message β€” Not just the last line. Include the entire stack trace. It contains clues about where the error originated.
  • The relevant code β€” The function or block where the error occurs. Include a few lines above and below.
  • What you expected to happen β€” "I expected this to return a list of users" helps the AI understand your intent.
  • What actually happened β€” "Instead, it returns an empty array" or "it crashes with this error."
  • What you've already tried β€” This prevents the AI from suggesting things you've already ruled out.

Think of it like a doctor's visit: the more symptoms you describe, the better the diagnosis.

Common Debugging Patterns AI Excels At

AI is particularly good at debugging these types of issues:

  • Type errors and null references β€” "Cannot read property of undefined" β€” AI instantly identifies the null value and suggests null checks or optional chaining
  • Async/await bugs β€” Forgetting await, race conditions, promise chains gone wrong
  • Off-by-one errors β€” Loop boundaries, array indexing, fence-post problems
  • Import/dependency issues β€” Wrong paths, circular imports, version mismatches
  • Logic errors β€” When the code runs but produces wrong results, AI can trace through the logic step by step

AI Debugging in Action: From Bug to Fix

# ===== THE BUGGY CODE =====
# A student writes this function to calculate average grades
def calculate_average(grades):
"""Calculate the average of a list of grades."""
total = 0
for grade in grades:
total += grade
average = total / len(grades) # Bug: crashes if grades is empty!
return round(average, 2)
def get_letter_grade(score):
"""Convert numeric score to letter grade."""
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# Test with normal data - works fine!
print("Test 1:", calculate_average([85, 92, 78, 95, 88]))
print("Grade:", get_letter_grade(calculate_average([85, 92, 78, 95, 88])))
# Test with empty list - BUG!
try:
print("Test 2:", calculate_average([]))
except ZeroDivisionError as e:
print(f"BUG! Error: {e}")
print("AI says: 'You're dividing by len(grades), but the list is")
print("empty so len(grades) is 0. Division by zero!'")
# ===== THE AI-SUGGESTED FIX =====
def calculate_average_fixed(grades):
"""Calculate the average of a list of grades (AI-fixed)."""
if not grades: # AI fix: handle empty list
return 0.0
total = sum(grades) # AI tip: use built-in sum()
return round(total / len(grades), 2)
print("\nFixed version:")
print("Test 1:", calculate_average_fixed([85, 92, 78, 95, 88]))
print("Test 2:", calculate_average_fixed([])) # No crash!
print("Test 3:", calculate_average_fixed([100])) # Edge case
Output
Test 1: 87.6
Grade: B
BUG! Error: division by zero
AI says: 'You're dividing by len(grades), but the list is
empty so len(grades) is 0. Division by zero!'

Fixed version:
Test 1: 87.6
Test 2: 0.0
Test 3: 100.0
Note: When AI debugging fails: AI struggles with bugs that require runtime context it can't see β€” race conditions in multi-threaded code, environment-specific issues (works on my machine!), bugs that depend on specific data in your database, or performance issues that only appear at scale. For these, AI is still useful for brainstorming hypotheses, but you'll need traditional debugging tools (breakpoints, profilers, logs) alongside it.

Pro Tips for AI Debugging

  • Use the "rubber duck" technique with AI: Explain the problem step by step to the AI. Often, the act of explaining helps you find the bug, and the AI catches what you miss.
  • Ask "why" not just "fix": Instead of "fix this code," ask "explain why this error is happening." Understanding the root cause prevents the same bug in the future.
  • Share the stack trace: The stack trace is a roadmap showing exactly where the error occurred and what called what. Always include it.
  • Test the fix: Don't just paste the AI's fix and move on. Run the code. Test edge cases. AI fixes sometimes introduce new bugs.
  • Learn from the pattern: If AI keeps fixing the same type of bug for you (null checks, async issues), study that pattern. The goal is to need AI less over time, not more.
Challenge

Quick check

What is the most common mistake people make when asking AI to debug their code?

Continue reading