- Learn
- Prompt Engineering
- Prompt Engineering for Debugging
Master prompting techniques specifically designed to help AI assist with debugging, error analysis, and problem-solving.
Prompt Engineering for Debugging
Debugging is one of the most valuable use cases for AI assistance. The right prompts can transform AI into a powerful debugging partner that helps you find and fix issues faster.
The Debugging Mindset
When debugging with AI, think of it as consulting an expert who:
- Wasn't there when you wrote the code
- Doesn't know your local environment
- Needs explicit context about what you've tried
The more context you provide, the better the diagnosis.
Essential Debugging Information
Always include these elements in debugging prompts:
| Element | Why It Matters |
|---|---|
| Error message | The starting point for diagnosis |
| Relevant code | Where the error occurs |
| Expected behavior | What should happen |
| Actual behavior | What actually happens |
| Environment | Node version, OS, dependencies |
| What you've tried | Avoid duplicate suggestions |
Basic Debugging Prompt Template
I'm encountering an error that I need help debugging.
**Error Message:**
[paste exact error message and stack trace]
**Relevant Code:**
```[language]
[paste the code where error occurs]
Expected Behavior: [what should happen]
Actual Behavior: [what actually happens]
Environment:
- Node.js: v20.10.0
- Framework: Next.js 14
- OS: macOS 14.2
What I've Tried:
- [attempt 1]
- [attempt 2]
Please help me:
- Understand why this error occurs
- Find the root cause
- Suggest a fix
## Error Type-Specific Prompts
### Runtime Errors
Debug this runtime error:
Error: TypeError: Cannot read properties of undefined (reading 'map') at ProductList (ProductList.tsx:23:18) at renderWithHooks (react-dom.development.js:14985:18)
Code:
const ProductList = ({ products }) => {
return (
<div>
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
};
Context:
- Products are fetched from API in parent component
- API sometimes returns null instead of empty array
- Error happens intermittently
Analyze:
- Why does this error occur?
- What are all possible causes?
- What's the most robust fix?
### Async/Timing Errors
I have a race condition or timing issue.
Symptom: Data sometimes shows stale values after update.
Code:
const updateUser = async (userId: string, data: UpdateData) => {
await api.updateUser(userId, data);
const updatedUser = await api.getUser(userId);
setUser(updatedUser);
};
Environment:
- React 18 with concurrent features enabled
- Using React Query for data fetching
Questions:
- Is this actually a race condition?
- What could cause stale data?
- How should I restructure this?
### Build/Compilation Errors
Getting a TypeScript compilation error I don't understand.
Error:
TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
Code:
const processConfig = (config: Config) => {
const apiUrl = config.apiUrl; // string | undefined
fetchData(apiUrl); // fetchData expects string
};
I understand the error message, but I'm not sure the best way to handle this. What are my options and which is recommended?
### Memory Leaks
I suspect a memory leak in my React component.
Symptoms:
- Memory usage grows over time
- Performance degrades after extended use
- Chrome DevTools shows detached DOM nodes
Code:
useEffect(() => {
const socket = new WebSocket(WS_URL);
socket.onmessage = (event) => {
setMessages(prev => [...prev, JSON.parse(event.data)]);
};
return () => socket.close();
}, []);
Questions:
- Is there a memory leak in this code?
- What's causing it?
- How do I properly clean up?
## Progressive Debugging Strategy
### Step 1: Understand the Error
First, help me understand this error message:
Error: ENOENT: no such file or directory, open '/app/config/production.json'
What does this error mean, and what are the common causes?
### Step 2: Trace the Problem
Now I understand the error. Help me trace where it originates.
The error occurs when running: npm run build
Relevant files:
- webpack.config.js (uses config file)
- package.json scripts
- Directory structure
[paste relevant code]
Where in the build process does this fail?
### Step 3: Fix and Verify
Based on our analysis, the issue is [X].
Proposed fix: [your proposed fix]
Questions:
- Will this fix actually solve the problem?
- Are there edge cases I'm missing?
- Could this introduce new issues?
## Rubber Duck Debugging with AI
Use AI as an intelligent rubber duck:
I'm stuck on a bug and want to think through it out loud.
The Problem: Users report that sometimes their session expires immediately after login.
What I Know:
- Sessions are stored in Redis
- JWT tokens have 24-hour expiry
- Issue happens intermittently
- More common in production than staging
Let me walk through the login flow:
- User submits credentials
- Server validates and creates JWT
- JWT is stored in Redis with session data
- JWT is sent to client in HTTP-only cookie
Ask me questions to help me find the bug.
## Debugging Complex Systems
### Distributed System Debugging
I'm debugging an issue across multiple services.
Architecture:
- API Gateway (Kong)
- Auth Service (Node.js)
- User Service (Go)
- Database (PostgreSQL)
Problem: Intermittent 401 errors that don't reproduce locally.
Request Flow:
- Client -> Gateway (auth check passes)
- Gateway -> Auth Service (token validation)
- Auth Service -> User Service (get user details)
- Returns 401 randomly at step 3
Logs show no errors. What should I check?
### Database Query Debugging
This query is slow in production but fast locally.
Query:
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id
ORDER BY order_count DESC
LIMIT 100;
Execution times:
- Local (1000 rows): 50ms
- Production (2M rows): 45 seconds
EXPLAIN shows: [paste explain output]
What indexes should I add and why?
## Debugging Prompt Patterns
### The "What Changed" Pattern
This code was working yesterday, now it's broken.
What changed:
- Updated React from 18.2 to 18.3
- Added new ESLint rules
- Teammate merged PR #123
Error: [error message]
Which change likely caused this?
### The "Works/Doesn't Work" Pattern
Same function, different results:
This WORKS:
const result = await fetchData('users');
console.log(result); // [user1, user2]
This DOESN'T WORK:
const result = await fetchData('products');
console.log(result); // undefined
Both endpoints return valid JSON when tested with curl. Why does one work and not the other?
### The "Minimal Reproduction" Pattern
Help me create a minimal reproduction of this bug.
Original complex code that has the bug: [paste complex code]
I want to isolate the issue. What's the smallest piece of code that would reproduce this behavior?
## Common Debugging Mistakes to Avoid
### 1. Too Little Context
**Bad**:
Why is this broken? [single line of code]
**Good**:
This function throws an error when called with undefined. [full function with context about how/where it's called]
### 2. Omitting Error Messages
**Bad**:
My code doesn't work.
**Good**:
Error: TypeError: Cannot read properties of undefined Stack trace: [full stack trace]
### 3. Not Sharing What You've Tried
**Bad**:
How do I fix this null pointer error?
**Good**:
How do I fix this null pointer error? I've tried:
- Adding null checks (still occurs)
- Using optional chaining (different error)
- Checking API response (data exists)
## Practice Exercise
Create debugging prompts for these scenarios:
1. **A React component renders infinitely** - useEffect with dependencies issue
2. **API returns 500 but only on certain inputs** - Data validation problem
3. **Tests pass locally but fail in CI** - Environment difference
4. **CSS styles not applying** - Specificity or cascade issue
For each, include:
- Error/symptom description
- Relevant code
- Environment details
- Specific questions to ask
## Summary
- Always include error messages, code, expected/actual behavior
- Provide environment details and what you've tried
- Use progressive debugging: understand, trace, fix
- Create minimal reproductions for complex issues
- Be specific about what kind of help you need
## Next Steps
Now that you can debug effectively with AI, let's explore prompt engineering for refactoring—transforming working code into better code.