Intermediate22 min

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:

ElementWhy It Matters
Error messageThe starting point for diagnosis
Relevant codeWhere the error occurs
Expected behaviorWhat should happen
Actual behaviorWhat actually happens
EnvironmentNode version, OS, dependencies
What you've triedAvoid duplicate suggestions

Basic Debugging Prompt Template

Terminal
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:

  1. Understand why this error occurs
  2. Find the root cause
  3. Suggest a fix
Terminal

## 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:

Terminal
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:

  1. Why does this error occur?
  2. What are all possible causes?
  3. What's the most robust fix?
Terminal

### Async/Timing Errors

I have a race condition or timing issue.

Symptom: Data sometimes shows stale values after update.

Code:

Terminal
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:

  1. Is this actually a race condition?
  2. What could cause stale data?
  3. How should I restructure this?
Terminal

### Build/Compilation Errors

Getting a TypeScript compilation error I don't understand.

Error:

Terminal
TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

Code:

Terminal
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?

Terminal

### 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:

Terminal
useEffect(() => {
  const socket = new WebSocket(WS_URL);

  socket.onmessage = (event) => {
    setMessages(prev => [...prev, JSON.parse(event.data)]);
  };

  return () => socket.close();
}, []);

Questions:

  1. Is there a memory leak in this code?
  2. What's causing it?
  3. How do I properly clean up?
Terminal

## 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?

Terminal

### 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?

Terminal

### Step 3: Fix and Verify

Based on our analysis, the issue is [X].

Proposed fix: [your proposed fix]

Questions:

  1. Will this fix actually solve the problem?
  2. Are there edge cases I'm missing?
  3. Could this introduce new issues?
Terminal

## 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:

  1. User submits credentials
  2. Server validates and creates JWT
  3. JWT is stored in Redis with session data
  4. JWT is sent to client in HTTP-only cookie

Ask me questions to help me find the bug.

Terminal

## 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:

  1. Client -> Gateway (auth check passes)
  2. Gateway -> Auth Service (token validation)
  3. Auth Service -> User Service (get user details)
  4. Returns 401 randomly at step 3

Logs show no errors. What should I check?

Terminal

### Database Query Debugging

This query is slow in production but fast locally.

Query:

Terminal
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?

Terminal

## 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?

Terminal

### The "Works/Doesn't Work" Pattern

Same function, different results:

This WORKS:

Terminal
const result = await fetchData('users');
console.log(result); // [user1, user2]

This DOESN'T WORK:

Terminal
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?

Terminal

### 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?

Terminal

## Common Debugging Mistakes to Avoid

### 1. Too Little Context

**Bad**:

Why is this broken? [single line of code]

Terminal

**Good**:

This function throws an error when called with undefined. [full function with context about how/where it's called]

Terminal

### 2. Omitting Error Messages

**Bad**:

My code doesn't work.

Terminal

**Good**:

Error: TypeError: Cannot read properties of undefined Stack trace: [full stack trace]

Terminal

### 3. Not Sharing What You've Tried

**Bad**:

How do I fix this null pointer error?

Terminal

**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)
Terminal

## 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.
Mark this lesson as complete to track your progress