How to Debug Faster With AI
Most developers use AI wrong when they're stuck on a bug. Here's a repeatable process for describing problems clearly, iterating when the first answer misses, and making AI a genuine debugging partner rather than a fancy search engine.
Most developers who complain that AI isn't helpful for debugging are doing the same thing: pasting a cryptic error message with no context and expecting a useful answer. The AI has no idea what language version you're running, what your function is supposed to do, or what you've already tried. It's guessing.
This tutorial walks through a repeatable process for debugging with AI that actually works. The same five steps apply whether you're dealing with a Python type error, a JavaScript race condition, or a slow SQL query.
The Problem With How Most People Use AI for Debugging
The typical debugging session looks like this: copy the error message, paste it into Claude or ChatGPT, get a generic explanation of what that error type usually means, try the suggestion, it doesn't work, give up on AI and go back to Stack Overflow.
The problem isn't the AI. It's the prompt. "TypeError: cannot read property of undefined" has hundreds of possible causes. Without seeing the actual code and knowing what line it's failing on, no one — human or AI — can give you a targeted answer.
The 5-Step Debug Loop
Use this process every time you bring a bug to an AI. It takes 2 more minutes upfront and saves you 20 minutes of back-and-forth.
- 1Reproduce it reliably first — if you can't reproduce the bug consistently, you're debugging a ghost. Make sure you can trigger it on demand before involving AI.
- 2Gather the full context — the complete error message and stack trace, the relevant code (the function where it fails and any code that calls it), what you expected to happen, what actually happened, and anything you've already tried.
- 3Write a specific prompt — don't just dump everything in. Frame it clearly: here's the error, here's the code, here's what I expected, here's what I got. Ask for a step-by-step diagnosis, not just a fix.
- 4Evaluate the response critically — the AI's first answer is often right, but not always. Read the explanation before applying the fix. If the explanation doesn't match what you're seeing, say so.
- 5Iterate with feedback — if the fix doesn't work, tell the AI specifically what happened when you applied it. Don't start over from scratch; build on the conversation.
Writing a Good Debug Prompt
Here's the difference between a weak prompt and a strong one for the same bug.
"I'm getting an undefined error in my React app. How do I fix it?"
"I'm getting this error in a React 18 / TypeScript app:
TypeError: Cannot read properties of undefined (reading 'map')
at ProductList (ProductList.tsx:23)
Here's the component:
function ProductList({ products }) {
return (
<ul>
{products.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
)
}
The component is called like this: <ProductList products={data.items} />
The data comes from a fetch call. The error only happens on first load, not after a refresh.
Expected: list renders on first load.
Actual: crashes with the above error.
What's causing this and what's the fix?"Real Example — JavaScript Async Bug
Here's a realistic JavaScript bug. The function is supposed to fetch user data and then fetch their orders, but sometimes orders comes back empty even when the user definitely has orders.
async function getUserWithOrders(userId) {
const user = await fetchUser(userId)
fetchOrders(userId) // missing await
return { user, orders }
}"This async function is supposed to return a user and their orders, but orders is always undefined even when the user has orders.
async function getUserWithOrders(userId) {
const user = await fetchUser(userId)
fetchOrders(userId)
return { user, orders }
}
Expected: { user: {...}, orders: [...] }
Actual: { user: {...}, orders: undefined }
What's wrong?"The AI will immediately spot the missing await and the missing variable assignment on fetchOrders. It will also likely point out that orders is never declared — it would throw a ReferenceError in strict mode. Two bugs for the price of one prompt.
Real Example — SQL Query Returning Wrong Results
SQL bugs are particularly good candidates for AI debugging because you can share both the query and the schema, and ask for a walkthrough of exactly what the query is doing.
-- Tables: -- orders(id, user_id, total, status, created_at) -- users(id, name, email) -- Query trying to get total revenue per user for completed orders: SELECT u.name, SUM(o.total) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name HAVING o.status = 'completed'
"This SQL query is supposed to return total revenue per user, only for completed orders. It runs without error but returns wrong numbers — it seems to be including non-completed orders. -- Schema: -- orders(id, user_id, total, status, created_at) -- users(id, name, email) SELECT u.name, SUM(o.total) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name HAVING o.status = 'completed' Walk me through what this query is actually doing and what's wrong with it."
The AI will explain that HAVING is a filter on aggregated groups, not on individual rows — so it's filtering after the SUM is calculated, not before. The fix is to move the filter to a WHERE clause before the GROUP BY. It will also likely note that the HAVING condition references a non-aggregated column, which is invalid SQL in strict mode and may produce unpredictable results.
When the First Answer Doesn't Work
Don't give up and don't start a new conversation. Build on it. Tell the AI exactly what happened when you applied the fix.
- "I applied your fix but now I'm getting a different error: [paste new error]. Here's the updated code: [paste]"
- "That explanation makes sense but the fix didn't change the behaviour. The output is still [describe]. What else could be causing it?"
- "Your solution works but introduces a new problem — [describe]. How do I fix both?"
- "I think you misunderstood the issue. The bug isn't in [X], it's that [clarification]. Can you look at it again with that in mind?"
Ask AI to Write Diagnostic Tests Before the Fix
This is an underused technique: instead of asking the AI to fix your bug directly, ask it to write tests that expose the bug. This forces you to understand the failure mode before applying a fix, and gives you a test you can keep to prevent regression.
"Before you suggest a fix, write a unit test that demonstrates the bug in this function. I want a test that fails with the current code and will pass once the bug is fixed. Here's the function: [paste function] Here's what it's supposed to do: [describe] Here's what it actually does: [describe]"
Once you have the failing test, you can ask the AI to fix the function while keeping the test in view — or fix it yourself and verify with the test.
Bugs AI Is Especially Good At Diagnosing
- Off-by-one errors — trace through the logic and immediately spot boundary conditions
- Async/await mistakes — missing awaits, unhandled promises, incorrect Promise chaining
- Type errors — especially in TypeScript where the error messages can be cryptic
- SQL logic errors — wrong join types, WHERE vs HAVING, missing GROUP BY columns
- Regex — paste pattern and input and ask for a walkthrough of what it's matching
- Import/export issues — circular dependencies, missing default exports, CommonJS vs ESM conflicts
Bugs AI Struggles With
- Timing and environment issues — bugs that depend on race conditions, specific hardware, or production-only config
- Bugs in code the AI can't see — if the issue is in a library you didn't paste, it's guessing
- Intermittent failures with no clear pattern — if you can't reproduce it reliably, neither can the AI's analysis
- Performance bugs at scale — the AI can spot algorithmic issues but can't run benchmarks
A Quick Reference: Debugging Prompt Templates
-- Basic error prompt: "Error: [paste]. Code: [paste]. Expected: [describe]. Actual: [describe]. What's wrong?" -- For intermittent bugs: "This bug occurs [frequency] in [environment]. Here's what I know: [details]. What are the most likely causes? What logging would help me catch it?" -- For logic bugs with no error: "This function produces [wrong output] instead of [expected output]. Trace through the logic step by step and find where it goes wrong: [paste code]" -- For iterating after a failed fix: "I applied your fix but it didn't change the behaviour / caused a new error: [describe]. Updated code: [paste]. What's still wrong?" -- For getting a test before the fix: "Write a unit test that exposes this bug. I want it to fail now and pass after the fix: [paste code + describe bug]"
Ready to go further?
Take the interactive course — daily lessons, real exercises, XP and streaks. Turn reading into lasting skills.
