debugger

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Debugger

调试指南

An advanced debugging specialist that helps diagnose and resolve code issues systematically.
这是一个高级调试专家,可系统地帮助诊断和解决代码问题。

When This Skill Activates

该技能的触发场景

Activates when you:
  • Report an error or bug
  • Mention "debug this" or "help debug"
  • Describe unexpected behavior
  • Ask why something isn't working
当你出现以下情况时,该技能会激活:
  • 报告错误或bug
  • 提及“调试这个”或“帮忙调试”
  • 描述意外行为
  • 询问某功能为何无法正常工作

Debugging Process

调试流程

Phase 1: Understand the Problem

阶段1:理解问题

  1. Reproduce the issue
    • What are the exact steps to reproduce?
    • What is the expected behavior?
    • What is the actual behavior?
    • What error messages appear?
  2. Gather context
    bash
    # Check recent changes
    git log --oneline -10
    
    # Check error logs
    tail -f logs/error.log
    
    # Check environment
    env | grep -i debug
  1. 复现问题
    • 复现问题的确切步骤是什么?
    • 预期行为是什么?
    • 实际行为是什么?
    • 出现了哪些错误信息?
  2. 收集上下文信息
    bash
    # 查看最近的变更
    git log --oneline -10
    
    # 查看错误日志
    tail -f logs/error.log
    
    # 查看环境变量
    env | grep -i debug

Phase 2: Isolate the Issue

阶段2:定位问题

  1. Locate the error source
    • Stack trace analysis
    • Error code lookup
    • Log correlation
  2. Narrow down scope
    • Binary search (comment out half)
    • Minimize reproduction case
    • Identify affected components
  1. 定位错误来源
    • 堆栈跟踪分析
    • 错误代码查询
    • 日志关联分析
  2. 缩小问题范围
    • 二分法排查(注释掉一半代码)
    • 简化复现案例
    • 确定受影响的组件

Phase 3: Analyze the Root Cause

阶段3:分析根本原因

Common Error Categories

常见错误类别

CategorySymptomsInvestigation Steps
Null/Undefined"Cannot read X of undefined"Trace the variable origin
Type Errors"X is not a function"Check actual vs expected type
Async IssuesRace conditions, timingCheck promise handling, async/await
State IssuesStale data, wrong stateTrace state mutations
NetworkTimeouts, connection refusedCheck endpoints, CORS, auth
EnvironmentWorks locally, not in prodCompare env vars, versions
MemoryLeaks, OOMProfile memory usage
ConcurrencyDeadlocks, race conditionsCheck locks, shared state
类别症状排查步骤
空值/未定义"Cannot read X of undefined"追踪变量的来源
类型错误"X is not a function"检查实际类型与预期类型是否一致
异步问题竞态条件、时序问题检查Promise处理、async/await使用
状态问题数据过期、状态异常追踪状态变更过程
网络问题超时、连接被拒绝检查端点、CORS、认证信息
环境问题本地正常但生产环境异常对比环境变量、版本差异
内存问题内存泄漏、内存不足(OOM)分析内存使用情况
并发问题死锁、竞态条件检查锁机制、共享状态

Phase 4: Form Hypotheses

阶段4:提出假设

For each potential cause:
  1. Form a hypothesis
  2. Create a test to validate
  3. Run the test
  4. Confirm or reject
针对每个潜在原因:
  1. 提出假设
  2. 设计测试方案验证假设
  3. 执行测试
  4. 确认或推翻假设

Phase 5: Fix and Verify

阶段5:修复与验证

  1. Implement the fix
  2. Add logging if needed
  3. Test the fix
  4. Add regression test
  1. 实施修复方案
  2. 必要时添加日志
  3. 测试修复效果
  4. 添加回归测试

Debugging Commands

调试命令

General Debugging

通用调试命令

bash
undefined
bash
undefined

Find recently modified files

查找最近修改的文件

find . -type f -mtime -1 -name ".js" -o -name ".ts" -o -name "*.py"
find . -type f -mtime -1 -name ".js" -o -name ".ts" -o -name "*.py"

Grep for error patterns

搜索错误模式

grep -r "ERROR|FATAL|Exception" logs/
grep -r "ERROR|FATAL|Exception" logs/

Search for suspicious patterns

搜索可疑标记

grep -r "TODO|FIXME|XXX" src/
grep -r "TODO|FIXME|XXX" src/

Check for console.log left in code

检查代码中遗留的console.log

grep -r "console.log|debugger" src/
undefined
grep -r "console.log|debugger" src/
undefined

Language-Specific

语言专属命令

JavaScript/TypeScript:
bash
undefined
JavaScript/TypeScript:
bash
undefined

Run with debug output

启用调试输出运行

NODE_DEBUG=* node app.js
NODE_DEBUG=* node app.js

Check syntax

检查语法

node -c file.js
node -c file.js

Run tests in debug mode

以调试模式运行测试

npm test -- --inspect-brk

**Python:**
```bash
npm test -- --inspect-brk

**Python:**
```bash

Run with pdb

使用pdb运行脚本

python -m pdb script.py
python -m pdb script.py

Check syntax

检查语法

python -m py_compile script.py
python -m py_compile script.py

Verbose mode

详细模式运行

python -v script.py

**Go:**
```bash
python -v script.py

**Go:**
```bash

Race detection

竞态检测

go run -race main.go
go run -race main.go

Debug build

编译调试版本

go build -gcflags="-N -l"
go build -gcflags="-N -l"

Profile

性能分析

go test -cpuprofile=cpu.prof
undefined
go test -cpuprofile=cpu.prof
undefined

Common Debugging Patterns

常见调试模式

Pattern 1: Divide and Conquer

模式1:分治排查

python
undefined
python
undefined

When you don't know where the bug is:

当不知道bug位置时:

def process(): step1() step2() step3() step4()
def process(): step1() step2() step3() step4()

Comment out half:

注释掉一半代码:

def process(): step1() # step2() # step3() # step4()
def process(): step1() # step2() # step3() # step4()

If bug disappears, uncomment half of commented:

如果bug消失,取消注释一半代码:

def process(): step1() step2() # step3() # step4()
def process(): step1() step2() # step3() # step4()

Continue until you isolate the bug

重复此过程直到定位bug

undefined
undefined

Pattern 2: Add Logging

模式2:添加日志

typescript
// Before (mysterious failure):
async function getUser(id: string) {
  const user = await db.find(id);
  return transform(user);
}

// After (with logging):
async function getUser(id: string) {
  console.log('[DEBUG] getUser called with id:', id);
  const user = await db.find(id);
  console.log('[DEBUG] db.find returned:', user);
  const result = transform(user);
  console.log('[DEBUG] transform returned:', result);
  return result;
}
typescript
// 修复前(故障原因不明):
async function getUser(id: string) {
  const user = await db.find(id);
  return transform(user);
}

// 修复后(添加日志):
async function getUser(id: string) {
  console.log('[DEBUG] getUser called with id:', id);
  const user = await db.find(id);
  console.log('[DEBUG] db.find returned:', user);
  const result = transform(user);
  console.log('[DEBUG] transform returned:', result);
  return result;
}

Pattern 3: Minimal Reproduction

模式3:简化复现案例

typescript
// Complex code with bug:
function processBatch(items, options) {
  // 100 lines of complex logic
}

// Create minimal reproduction:
function processBatch(items, options) {
  console.log('Items:', items.length);
  console.log('Options:', options);
  // Test with minimal data
  return processBatch([items[0]], options);
}
typescript
// 存在bug的复杂代码:
function processBatch(items, options) {
  // 100行复杂逻辑
}

// 创建简化的复现案例:
function processBatch(items, options) {
  console.log('Items:', items.length);
  console.log('Options:', options);
  // 使用最小数据集测试
  return processBatch([items[0]], options);
}

Error Message Analysis

错误信息分析

Common Error Messages

常见错误信息

ErrorLikely CauseSolution
Cannot read property 'X' of undefined
Accessing property on null/undefinedAdd null check, use optional chaining
X is not a function
Wrong type, shadowingCheck typeof, verify import
Unexpected token
Syntax errorCheck line before error, validate syntax
Module not found
Import path wrongCheck relative path, verify file exists
EADDRINUSE
Port already in useKill existing process, use different port
Connection refused
Service not runningStart service, check port
Timeout
Request too slowIncrease timeout, check network
错误信息可能原因解决方案
Cannot read property 'X' of undefined
访问了null/undefined对象的属性添加空值检查,使用可选链操作符
X is not a function
类型错误、变量被遮蔽检查类型,验证导入是否正确
Unexpected token
语法错误检查错误行的上一行代码,验证语法
Module not found
导入路径错误检查相对路径,验证文件是否存在
EADDRINUSE
端口已被占用终止现有进程,使用其他端口
Connection refused
服务未运行启动服务,检查端口是否正确
Timeout
请求过慢增加超时时间,检查网络状况

Debugging Checklist

调试检查清单

  • I can reproduce the issue consistently
  • I have identified the exact error location
  • I understand the root cause
  • I have a proposed fix
  • The fix doesn't break existing functionality
  • I've added a test to prevent regression
  • 我能稳定复现该问题
  • 我已定位到确切的错误位置
  • 我理解问题的根本原因
  • 我有可行的修复方案
  • 修复不会破坏现有功能
  • 我已添加回归测试以防止问题复发

Scripts

脚本

Generate a debug report:
bash
python scripts/debug_report.py <error-message>
生成调试报告:
bash
python scripts/debug_report.py <error-message>

References

参考资料

  • references/checklist.md
    - Debugging checklist
  • references/patterns.md
    - Common debugging patterns
  • references/errors.md
    - Error message reference
  • references/checklist.md
    - 调试检查清单
  • references/patterns.md
    - 常见调试模式
  • references/errors.md
    - 错误信息参考手册