Debugging Prompt Templates

AI prompt templates for debugging code. Identify issues, understand errors, and find solutions faster.

Overview

Debugging is where developers spend most of their time, yet most bug reports to AI lack the context needed for accurate diagnosis. These prompts help you describe bugs in ways that lead to actual solutions, not generic advice. The key is providing error messages, expected vs. actual behavior, and what you've already tried.

Best Practices

1

Always include the exact error message, copy it verbatim rather than paraphrasing

2

Describe both expected behavior and actual behavior to clarify what 'broken' means

3

Include the relevant code snippet, not just a description of what it does

4

List what you've already tried so the AI doesn't suggest things you've ruled out

5

Specify your environment (OS, language version, framework version) when it might be relevant

Prompt Templates

1. Error Message Diagnosis

Help me debug this error:

**Error message:**
```
[PASTE FULL ERROR MESSAGE AND STACK TRACE]
```

**Code causing the error:**
```[LANGUAGE]
[RELEVANT CODE SNIPPET]
```

**Context:**
- What I'm trying to do: [GOAL]
- When it happens: [ALWAYS / INTERMITTENT / SPECIFIC CONDITIONS]
- Environment: [LANGUAGE VERSION, OS, FRAMEWORK]

**Already tried:**
- [WHAT YOU'VE ATTEMPTED]

Explain what's causing this error and provide a fix.
Error: TypeError: Cannot read properties of undefined (reading 'map')
Code: React component that renders a list of users from an API call
When: Only on first render, works after refresh
Environment: React 18, Node 18
Already tried: Adding null check with &&
**Root Cause:** The component renders before the API call completes. On first render, `users` is undefined, and you're calling `.map()` on undefined.

**The Issue with &&:** Your null check `users && users.map()` doesn't work because `users` is initialized as `undefined`, not `null`.

**Fix:**
```javascript
// Option 1: Initialize as empty array
const [users, setUsers] = useState([]);

// Option 2: Optional chaining with fallback
{(users ?? []).map(user =>...)}

// Option 3: Early return while loading
if (!users) return <LoadingSpinner />;
```

Option 1 is cleanest, initializing as `[]` means `.map()` always works (returns empty array while loading).

When you have a specific error message and need to understand what's causing it

  • Include the full stack trace, it often points to the exact line and call chain
  • Mention if the error is new or if you're working with code that was working before

2. Logic Bug Investigation

My code runs without errors but produces wrong results:

**Code:**
```[LANGUAGE]
[PASTE CODE]
```

**Expected behavior:**
[WHAT SHOULD HAPPEN]

**Actual behavior:**
[WHAT ACTUALLY HAPPENS]

**Test case:**
- Input: [SPECIFIC INPUT THAT FAILS]
- Expected output: [WHAT YOU EXPECT]
- Actual output: [WHAT YOU GET]

Walk me through the logic step by step and identify where it goes wrong.
Code: Function to calculate compound interest
Expected: $1,100 for $1000 at 10% for 1 year
Actual: $1,010
Input: principal=1000, rate=10, years=1
**Walking through your code:**

Line 3: `rate = rate`, You're not converting the percentage. When you pass `10`, you're using 10 (1000%) instead of 0.10 (10%).

**The bug:** Your formula treats the rate as a decimal but your input is a percentage.

**Fix:**
```python
def compound_interest(principal, rate, years):
 rate = rate / 100 # Convert percentage to decimal
 return principal * (1 + rate) ** years
```

**Verification:**
- Input: 1000, 10, 1
- Calculation: 1000 × (1 + 0.10)¹ = 1000 × 1.10 = 1100 ✓

When code executes without errors but gives incorrect results, the hardest bugs to find

  • Always provide a specific failing test case, not just a description of wrong output
  • Walk through the code yourself first with print statements, then share those outputs too

3. Intermittent Bug Analysis

Help me debug an intermittent issue:

**The problem:**
[DESCRIBE WHAT GOES WRONG]

**Frequency:**
[HOW OFTEN - e.g. 1 in 10 requests, only under load, random]

**When it happens:**
- Conditions that seem to trigger it: [ANY PATTERNS]
- Conditions when it works: [WHEN IT'S FINE]

**Relevant code:**
```[LANGUAGE]
[CODE THAT MIGHT BE INVOLVED]
```

**Environment:**
[CONCURRENT USERS, INFRASTRUCTURE, DATABASE]

**Logs from a failure:**
```
[ANY LOG OUTPUT FROM WHEN IT FAILED]
```

What are the most likely causes of this intermittent behavior?
Problem: Users randomly get logged out mid-session
Frequency: About 5% of sessions
Conditions: Seems more common when users have multiple tabs open
Environment: Node.js, Redis for sessions, load-balanced across 3 servers
**Most Likely Causes (in order of probability):**

1. **Session affinity issue with load balancer**
 With multiple servers and Redis, if sticky sessions aren't configured, requests might hit a server that doesn't have the session cached locally before Redis sync.
 - *Check:* Are you using `connect-redis` with proper configuration?
 - *Fix:* Ensure all session reads go through Redis, not local memory.

2. **Race condition with multiple tabs**
 Multiple tabs refreshing tokens simultaneously could invalidate each other's sessions.
 - *Check:* Log session token changes with timestamps
 - *Fix:* Implement token refresh locking

3. **Redis connection drops under load**
 Intermittent Redis connectivity could cause session lookups to fail.
 - *Check:* Monitor Redis connection errors
 - *Fix:* Add retry logic to session middleware

**Debugging steps:** Add logging for session operations with request IDs to trace the exact sequence when logouts occur.

For bugs that don't happen every time, race conditions, load-related issues, timing problems

  • Intermittent bugs are usually concurrency issues, caching problems, or environmental differences
  • Log MORE than you think you need, you can't reproduce intermittent bugs easily, so capture everything

4. Performance Bug Investigation

Help me debug a performance issue:

**The symptom:**
[WHAT'S SLOW - e.g. page load, API response, query]

**Measurements:**
- Current performance: [ACTUAL TIME/METRICS]
- Expected/acceptable: [TARGET]
- When it started: [ALWAYS SLOW / BECAME SLOW RECENTLY]

**What I've profiled:**
```
[ANY PROFILING DATA, SLOW QUERY LOGS, TIMING BREAKDOWNS]
```

**Relevant code:**
```[LANGUAGE]
[CODE PATH THAT'S SLOW]
```

**Scale:**
[DATA SIZE, CONCURRENT USERS, INFRASTRUCTURE]

Identify the likely bottleneck and suggest optimizations.
Symptom: API endpoint takes 8 seconds (should be under 500ms)
Measurements: Database queries take 7.2s of the 8s total
Slow query: SELECT with JOIN across 3 tables
Scale: Tables have 2M, 500K, and 100K rows respectively
**Bottleneck Identified:** The JOIN across 3 large tables is doing a full table scan.

**Analysis of your query:**
```sql
-- Your query scans all 2M rows before filtering
SELECT * FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN products p ON o.product_id = p.id
WHERE o.created_at > '2024-01-01'
```

**Issues:**
1. No index on `orders.created_at`
2. `SELECT *` fetches columns you likely don't need
3. No index on join columns

**Fixes (in order of impact):**

1. Add composite index:
```sql
CREATE INDEX idx_orders_date_customer_product 
ON orders(created_at, customer_id, product_id);
```

2. Select only needed columns:
```sql
SELECT o.id, o.total, c.name, p.title FROM...
```

**Expected improvement:** 8s → 50-100ms with proper indexing

When something that should be fast is slow, API endpoints, database queries, page loads

  • Always profile before improving, measure, don't guess where time is spent
  • Database issues account for 80%+ of backend performance problems

Common Mistakes to Avoid

Describing the error vaguely ('it doesn't work') instead of providing exact error messages and outputs

Not including what you've already tried, leading to suggestions you've already ruled out

Sharing too little code (hiding context) or too much code (thousands of lines without focus)

Frequently Asked Questions

Debugging is where developers spend most of their time, yet most bug reports to AI lack the context needed for accurate diagnosis. These prompts help you describe bugs in ways that lead to actual solutions, not generic advice. The key is providing error messages, expected vs. actual behavior, and what you've already tried.

Related Templates

Have your own prompt to optimize?