# debugging-issues > Debug production issues and errors systematically. Use when investigating bugs, errors, crashes, or unexpected behavior. - Author: Ali Haydar - Repository: AHaydar/ali-dev-tools - Version: 20251221182646 - Stars: 0 - Forks: 0 - Last Updated: 2026-02-07 - Source: https://github.com/AHaydar/ali-dev-tools - Web: https://mule.run/skillshub/@@AHaydar/ali-dev-tools~debugging-issues:20251221182646 --- --- name: debugging-issues description: Debug production issues and errors systematically. Use when investigating bugs, errors, crashes, or unexpected behavior. --- # Debugging Issues ## Debugging Workflow Copy and track progress: ``` Debug Progress: - [ ] Reproduce the issue reliably - [ ] Gather error logs and context - [ ] Form hypothesis about root cause - [ ] Test hypothesis with minimal change - [ ] Verify fix and add regression test ``` ## Step 1: Reproduce Reliably **Cannot debug what you can't reproduce.** ```bash # Gather reproduction steps 1. What exact actions trigger the issue? 2. Does it happen every time or intermittently? 3. What's the environment (browser, OS, data state)? 4. Can you reproduce in dev/staging? ``` **For intermittent issues:** - Add detailed logging before the failure point - Check for race conditions - Look for shared state or timing dependencies ## Step 2: Gather Information **Error logs:** ```bash # Check application logs tail -f /var/log/app.log # Check error tracking (Sentry, Rollbar) # Look for stack traces, user context, breadcrumbs # Browser console errors # Network tab for API failures ``` **System context:** ```bash # What changed recently? git log --since="1 week ago" --oneline # Check deployment logs # Check recent config changes # Check database migrations ``` ## Step 3: Form Hypothesis **Use scientific method:** ```markdown **Symptom:** API returns 500 error on POST /orders **Observations:** - Only happens for orders >$1000 - Started after yesterday's deploy - Error log shows "Column 'discount' not found" **Hypothesis:** Recent schema change added 'discount' column, but old code doesn't set it and it's NOT NULL. **Test:** Check if discount column is nullable. Add default value or update INSERT query. ``` ## Step 4: Isolate the Problem **Binary search approach:** ```javascript // Add console.log to narrow down console.log('Before calculation:', items) // ✅ Works const total = calculateTotal(items) console.log('After calculation:', total) // ❌ Fails here // Problem is in calculateTotal ``` **Simplify to minimal reproduction:** ```javascript // Original complex failing case processOrder({ items: [...100 items], user: {...}, payment: {...} }) // Simplify to minimal case processOrder({ items: [{ id: 1, price: 1500 }] }) // Still fails? Problem is in core logic, not data complexity ``` ## Common Bug Patterns ### Async Issues ```javascript // ❌ Race condition async function loadUser() { const user = await fetchUser() this.user = user // Component might unmount before this } // ✅ Check if still mounted async function loadUser() { const user = await fetchUser() if (this.isMounted) { this.user = user } } ``` ### State Management ```javascript // ❌ Mutating state directly users.push(newUser) // React won't detect change // ✅ Create new array setUsers([...users, newUser]) ``` ### Off-by-One ```javascript // ❌ Excludes last item for (let i = 0; i < array.length - 1; i++) // ✅ Includes all items for (let i = 0; i < array.length; i++) ``` ### Null/Undefined ```javascript // ❌ Assumes data exists const title = post.author.name // Crashes if author is null // ✅ Safe access const title = post?.author?.name ?? 'Unknown' ``` ## Debugging Tools ### Browser DevTools ```javascript // Breakpoint in code debugger // Conditional breakpoint (right-click in DevTools) // Break when: userId === '123' // Log without modifying code // Right-click line → Add logpoint ``` ### Node.js Debugging ```bash # Start with inspector node --inspect-brk app.js # Attach debugger in VSCode or Chrome DevTools # chrome://inspect ``` ### Database Debugging ```sql -- Enable query logging SET log_statement = 'all'; -- Check slow queries SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10; -- Explain query plan EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123; ``` ## Production Debugging **Never debug directly in production.** **Safe approaches:** ```bash # 1. Increase logging temporarily LOG_LEVEL=debug npm start # 2. Reproduce in staging with production data (anonymized) pg_dump production | pg_restore staging # 3. Add feature flag for debug mode if (debugMode) { console.log('Detailed state:', state) } ``` ## Step 5: Verify Fix **After fixing:** 1. Verify original reproduction case works 2. Test related functionality (regression check) 3. Add test to prevent future regression 4. Deploy to staging first 5. Monitor error rates after production deploy ```javascript // Add regression test test('handles orders over $1000', () => { const order = { items: [{ price: 1500 }] } expect(() => processOrder(order)).not.toThrow() }) ``` ## When Stuck **Try these:** 1. **Rubber duck debugging**: Explain problem out loud 2. **Take a break**: Fresh perspective helps 3. **Revert recent changes**: Confirm it worked before 4. **Ask for help**: Share stack trace and reproduction steps 5. **Read error message carefully**: Often contains the answer ## Quick Debugging Checklist **For errors:** - [ ] Read full error message and stack trace - [ ] Check recent code/config changes - [ ] Verify environment (dev vs prod differences) - [ ] Check dependencies (package versions) - [ ] Review logs around the error time **For unexpected behavior:** - [ ] Confirm expected vs actual behavior - [ ] Add logging at decision points - [ ] Check data state (DB, cache, localStorage) - [ ] Verify assumptions about data shape - [ ] Test with simplified input