介绍
# debug-pro
系统化的调试方法论及特定语言的调试命令。
## 7 步调试协议
1. **复现** — 使其持续失败。记录确切的步骤、输入和环境。 2. **隔离** — 缩小范围。注释代码、使用二分查找、用 `git bisect` 检查最近的提交。 3. **假设** — 针对根本原因形成一个具体的、可验证的理论。 4. **插桩** — 添加有针对性的日志、断言或断点。 5. **验证** — 确认根本原因。如果假设错误,返回第 3 步。 6. **修复** — 应用最小的正确修复。调试时抵制重构的冲动。 7. **回归测试** — 编写一个能捕获该错误的测试。确保测试通过。
## 特定语言的调试
### JavaScript / TypeScript ```bash # Node.js debugger node --inspect-brk app.js # Chrome DevTools: chrome://inspect
# Console debugging console.log(JSON.stringify(obj, null, 2)) console.trace('Call stack here') console.time('perf'); /* code */ console.timeEnd('perf')
# Memory leaks node --expose-gc --max-old-space-size=4096 app.js ```
### Python ```bash # Built-in debugger python -m pdb script.py
# Breakpoint in code breakpoint() # Python 3.7+
# Verbose tracing python -X tracemalloc script.py
# Profile python -m cProfile -s cumulative script.py ```
### Swift ```bash # LLDB debugging lldb ./MyApp (lldb) breakpoint set --name main (lldb) run (lldb) po myVariable
# Xcode: Product → Profile (Instruments) ```
### CSS / 布局 ```css /* Outline all elements */ * { outline: 1px solid red !important; }
/* Debug specific element */ .debug { background: rgba(255,0,0,0.1) !important; } ```
### 网络 ```bash # HTTP debugging curl -v https://api.example.com/endpoint curl -w "@curl-format.txt" -o /dev/null -s https://example.com
# DNS dig example.com nslookup example.com
# Ports lsof -i :3000 netstat -tlnp ```
### Git Bisect ```bash git bisect start git bisect bad # Current commit is broken git bisect good abc1234 # Known good commit # Git checks out middle commit — test it, then: git bisect good # or git bisect bad # Repeat until root cause commit is found git bisect reset ```
## 常见错误模式
| 错误 | 可能原因 | 修复方法 | |-------|-------------|-----| | `Cannot read property of undefined` | 缺少 null 检查或数据结构错误 | 添加可选链 (`?.`) 或验证数据 | | `ENOENT` | 文件/目录不存在 | 检查路径,创建目录,使用 `existsSync` | | `CORS error` | 后端缺少 CORS 头 | 添加配置了正确源的 CORS 中间件 | | `Module not found` | 缺少依赖或导入路径错误 | `npm install`,检查 tsconfig 路径 | | `Hydration mismatch` (React) | 服务端/客户端渲染的 HTML 不一致 | 确保渲染一致,对仅客户端逻辑使用 `useEffect` | | `Segmentation fault` | 内存损坏,空指针 | 检查数组边界、指针有效性 | | `Connection refused` | 服务未在预期端口运行 | 检查服务是否启动,验证端口/主机 | | `Permission denied` | 文件/网络权限问题 | 检查 chmod、防火墙、sudo |
## 快速诊断命令
```bash # What's using this port? lsof -i :PORT
# What's this process doing? ps aux | grep PROCESS
# Watch file changes fswatch -r ./src
# Disk space df -h
# System resource usage top -l 1 | head -10 ```