
关于
使用经过验证的调试技术系统性地查找和修复 Bug。从症状追溯到根因,实施修复并防止回归。
name: bug-hunter description: "使用经过验证的调试技术系统性地查找和修复 bug。从症状追溯到根本原因,实施修复并防止回归。" category: development risk: safe source: community date_added: "2026-03-05"
Bug 猎手
使用经过验证的调试技术系统性地追踪和修复 bug。不靠猜测——跟随证据。
何时使用此技能
- 用户报告了 bug 或错误
- 某些功能未按预期工作
- 用户说"修复 bug"或"调试这个"
- 间歇性故障或异常行为
- 生产环境问题需要调查
调试流程
1. 复现 Bug
首先,使其稳定复现:
1. 获取精确的复现步骤
2. 尝试在本地复现
3. 记录触发条件
4. 记录错误消息/行为
5. 检查是每次都发生还是随机发生
如果无法复现,收集更多信息:
- 什么环境?(开发、预发布、生产)
- 什么浏览器/设备?
- 之前有什么用户操作?
- 有错误日志吗?
2. 收集证据
收集所有可用信息:
检查日志:
# Application logs
tail -f logs/app.log
# System logs
journalctl -u myapp -f
# Browser console
# Open DevTools → Console tab
检查错误消息:
- 完整堆栈跟踪
- 错误类型和消息
- 行号
- 时间戳
检查状态:
- 正在处理什么数据?
- 用户试图做什么?
- 数据库中有什么?
- 本地存储/Cookie 中有什么?
3. 形成假设
基于证据,推测问题所在:
"登录超时是因为会话 cookie 在认证检查完成前过期"
"表单失败是因为邮箱验证正则不处理加号"
"API 返回 500 是因为数据库查询在特殊字符处有语法错误"
4. 验证假设
证明或推翻你的推测:
添加日志:
console.log('Before API call:', userData);
const response = await api.login(userData);
console.log('After API call:', response);
使用调试器:
debugger; // Execution pauses here
const result = processData(input);
隔离问题:
// Comment out code to narrow down
// const result = complexFunction();
const result = { mock: 'data' }; // Use mock data
5. 找到根本原因
追溯到实际问题:
常见根本原因:
- 空值/未定义值
- 错误的数据类型
- 竞态条件
- 缺少错误处理
- 逻辑错误
- 差一错误
- 异步/等待问题
- 缺少验证
示例追溯:
症状:"Cannot read property 'name' of undefined"
↓
位置:user.profile.name
↓
原因:user.profile 是 undefined
↓
原因:API 没有返回 profile
↓
原因:User ID 为 null
↓
根本原因:登录时没有在会话中设置 user ID
6. 实施修复
修复根本原因,而非症状:
错误的修复(症状):
// Just hide the error
const name = user?.profile?.name || 'Unknown';
正确的修复(根本原因):
// Ensure user ID is set on login
const login = async (credentials) => {
const user = await authenticate(credentials);
if (user) {
session.userId = user.id; // Fix: Set user ID
return user;
}
throw new Error('Invalid credentials');
};
7. 测试修复
验证它确实有效:
1. 复现原始 bug
2. 应用修复
3. 再次尝试复现(应该失败)
4. 测试边界情况
5. 测试相关功能
6. 运行现有测试
8. 防止回归
添加测试以确保不会再次出现:
test('login sets user ID in session', async () => {
const user = await login({ email: 'test@example.com', password: 'pass' });
expect(session.userId).toBe(user.id);
expect(session.userId).not.toBeNull();
});
调试技术
二分查找法
反复将问题空间减半:
// Does the bug happen before or after this line?
console.log('CHECKPOINT 1');
// ... code ...
console.log('CHECKPOINT 2');
// ... code ...
console.log('CHECKPOINT 3');
橡皮鸭调试法
逐行大声解释代码。通常在解释过程中就能发现问题。
打印调试法
策略性的 console.log:
console.log('Input:', input);
console.log('After transform:', transformed);
console.log('Before save:', data);
console.log('Result:', result);
差异调试法
比较正常与异常:
- 最近改了什么?
- 环境之间有什么不同?
- 数据有什么不同?
时间旅行调试法
使用 git 找到何时出错:
git bisect start
git bisect bad # Current commit is broken
git bisect good abc123 # This old commit worked
# Git will check out commits for you to test
常见 Bug 模式
空值/未定义
// Bug
const name = user.profile.name;
// Fix
const name = user?.profile?.name || 'Unknown';
// Better fix
if (!user || !user.profile) {
throw new Error('User p
兼容工具
Claude CodeCursor
标签
AI与机器学习