bug-detective
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBug Detective
错误侦探
A systematic debugging workflow for investigating and resolving code errors, exceptions, and failures. Provides structured debugging methods and common error pattern recognition.
用于排查和解决代码错误、异常、运行失败问题的系统化调试工作流,提供结构化的调试方法和常见错误模式识别能力。
Core Philosophy
核心原则
Debugging is a scientific problem-solving process that requires:
- Understand the problem - Clearly define symptoms and expected behavior
- Gather evidence - Collect error messages, logs, stack traces
- Form hypotheses - Infer possible causes based on evidence
- Verify hypotheses - Confirm or eliminate causes through experiments
- Resolve the issue - Apply fixes and verify
调试是科学的问题解决过程,需要遵循以下步骤:
- 理解问题 - 明确定义问题症状和预期行为
- 收集证据 - 收集错误信息、日志、栈轨迹
- 提出假设 - 基于证据推断可能的原因
- 验证假设 - 通过实验确认或排除原因
- 解决问题 - 应用修复并验证效果
Debugging Workflow
调试工作流
Step 1: Understand the Problem
步骤1:理解问题
Before starting to debug, clarify the following information:
Required information to collect:
- Complete error message content
- Exact location of the error (filename and line number)
- Reproduction steps (how to trigger the error)
- Expected behavior vs actual behavior
- Environment info (OS, versions, dependencies)
Question template:
1. What is the exact error message?
2. Which file and line does the error occur at?
3. How can this issue be reproduced? Provide detailed steps.
4. What was the expected result? What actually happened?
5. What recent changes might have introduced this issue?开始调试前,先明确以下信息:
需要收集的信息:
- 完整的错误信息内容
- 错误发生的准确位置(文件名和行号)
- 复现步骤(如何触发错误)
- 预期行为与实际行为的差异
- 环境信息(操作系统、版本、依赖)
问题模板:
1. What is the exact error message?
2. Which file and line does the error occur at?
3. How can this issue be reproduced? Provide detailed steps.
4. What was the expected result? What actually happened?
5. What recent changes might have introduced this issue?Step 2: Analyze Error Type
步骤2:分析错误类型
Choose a debugging strategy based on error type:
| Error Type | Characteristics | Debugging Method |
|---|---|---|
| Syntax Error | Code cannot be parsed | Check syntax, bracket matching, quotes |
| Import Error | ModuleNotFoundError | Check module installation, path config |
| Type Error | TypeError | Check data types, type conversions |
| Attribute Error | AttributeError | Check if object attribute exists |
| Key Error | KeyError | Check if dictionary key exists |
| Index Error | IndexError | Check list/array index range |
| Null Reference | NoneType/NullPointerException | Check if variable is None |
| Network Error | ConnectionError/Timeout | Check network connection, URL, timeout settings |
| Permission Error | PermissionError | Check file permissions, user permissions |
| Resource Error | FileNotFoundError | Check if file path exists |
根据错误类型选择调试策略:
| 错误类型 | 特征 | 调试方法 |
|---|---|---|
| Syntax Error | 代码无法被解析 | 检查语法、括号匹配、引号 |
| Import Error | ModuleNotFoundError | 检查模块安装情况、路径配置 |
| Type Error | TypeError | 检查数据类型、类型转换逻辑 |
| Attribute Error | AttributeError | 检查对象属性是否存在 |
| Key Error | KeyError | 检查字典键是否存在 |
| Index Error | IndexError | 检查列表/数组索引范围 |
| Null Reference | NoneType/NullPointerException | 检查变量是否为None |
| Network Error | ConnectionError/Timeout | 检查网络连接、URL、超时设置 |
| Permission Error | PermissionError | 检查文件权限、用户权限 |
| Resource Error | FileNotFoundError | 检查文件路径是否存在 |
Step 3: Locate the Problem Source
步骤3:定位问题来源
Use the following methods to locate the issue:
1. Binary Search Method
- Comment out half the code, check if the problem persists
- Progressively narrow the scope until the problematic code is found
2. Log Tracing
- Add print/logging statements at key locations
- Track variable value changes
- Confirm code execution path
3. Breakpoint Debugging
- Use debugger breakpoint functionality
- Step through code execution
- Inspect variable state
4. Stack Trace Analysis
- Find the call chain from the stack trace in the error message
- Determine the direct cause of the error
- Trace back to the root cause
使用以下方法定位问题:
1. 二分查找法
- 注释掉一半代码,检查问题是否仍然存在
- 逐步缩小范围,直到找到问题代码
2. 日志追踪
- 在关键位置添加print/logging语句
- 跟踪变量值的变化
- 确认代码执行路径
3. 断点调试
- 使用调试器的断点功能
- 单步执行代码
- 检查变量状态
4. 栈轨迹分析
- 从错误信息的栈轨迹中找到调用链
- 确定错误的直接原因
- 回溯找到根本原因
Step 4: Form and Verify Hypotheses
步骤4:提出并验证假设
Hypothesis framework:
Hypothesis: [problem description] causes [error phenomenon]
Verification steps:
1. [verification method 1]
2. [verification method 2]
Expected results:
- If hypothesis is correct: [expected phenomenon]
- If hypothesis is wrong: [expected phenomenon]假设框架:
Hypothesis: [problem description] causes [error phenomenon]
Verification steps:
1. [verification method 1]
2. [verification method 2]
Expected results:
- If hypothesis is correct: [expected phenomenon]
- If hypothesis is wrong: [expected phenomenon]Step 5: Apply Fix
步骤5:应用修复
After fixing, verify:
- The original error is resolved
- No new errors have been introduced
- Related functionality still works correctly
- Tests added to prevent regression
修复完成后,验证以下内容:
- 原始错误已解决
- 没有引入新的错误
- 相关功能仍然正常运行
- 新增测试用例防止回归
Python Common Error Patterns
Python常见错误模式
1. Indentation Errors
1. 缩进错误
2. Mutable Default Arguments
2. 可变默认参数
3. Closure Issues in Loops
3. 循环中的闭包问题
4. Modifying a List While Iterating
4. 迭代时修改列表
5. Using is
for String Comparison
is5. 使用is
进行字符串比较
is6. Forgetting to Call super().__init__()
super().__init__()6. 忘记调用super().__init__()
super().__init__()JavaScript/TypeScript Common Error Patterns
JavaScript/TypeScript常见错误模式
1. this
Binding Issues
this1. this
绑定问题
this2. Async Error Handling
2. 异步错误处理
3. Object Reference Comparison
3. 对象引用比较
Bash/Zsh Common Error Patterns
Bash/Zsh常见错误模式
1. Spacing Issues
1. 空格问题
bash
undefinedbash
undefined❌ No spaces allowed in assignment
❌ No spaces allowed in assignment
name = "John" # Error: tries to run 'name' command
name = "John" # Error: tries to run 'name' command
✅ Correct assignment
✅ Correct assignment
name="John"
name="John"
❌ Missing spaces in conditional test
❌ Missing spaces in conditional test
if[$name -eq 1]; then # Error
if[$name -eq 1]; then # Error
✅ Correct
✅ Correct
if [ $name -eq 1 ]; then
undefinedif [ $name -eq 1 ]; then
undefined2. Quoting Issues
2. 引号问题
bash
undefinedbash
undefined❌ Variables not expanded inside single quotes
❌ Variables not expanded inside single quotes
echo 'The value is $var' # Output: The value is $var
echo 'The value is $var' # Output: The value is $var
✅ Use double quotes
✅ Use double quotes
echo "The value is $var" # Output: The value is actual_value
echo "The value is $var" # Output: The value is actual_value
❌ Using backticks for command substitution (confusing)
❌ Using backticks for command substitution (confusing)
result=
commandresult=
command✅ Use $()
✅ Use $()
result=$(command)
undefinedresult=$(command)
undefined3. Unquoted Variables
3. 未加引号的变量
bash
undefinedbash
undefined❌ Unquoted variable, empty value causes errors
❌ Unquoted variable, empty value causes errors
rm -rf $dir/* # If dir is empty, deletes all files in current directory
rm -rf $dir/* # If dir is empty, deletes all files in current directory
✅ Always quote variables
✅ Always quote variables
[ -n "$dir" ] && rm -rf "$dir"/*
[ -n "$dir" ] && rm -rf "$dir"/*
Or use set -u to prevent undefined variables
Or use set -u to prevent undefined variables
set -u # or set -o nounset
undefinedset -u # or set -o nounset
undefined4. Variable Scope in Loops
4. 循环中的变量作用域
bash
undefinedbash
undefined❌ Pipe creates subshell, outer variable unchanged
❌ Pipe creates subshell, outer variable unchanged
cat file.txt | while read line; do
count=$((count + 1)) # Outer count won't change
done
echo "Total: $count" # Outputs 0
cat file.txt | while read line; do
count=$((count + 1)) # Outer count won't change
done
echo "Total: $count" # Outputs 0
✅ Use process substitution or redirection
✅ Use process substitution or redirection
while read line; do
count=$((count + 1))
done < file.txt
echo "Total: $count" # Correct output
undefinedwhile read line; do
count=$((count + 1))
done < file.txt
echo "Total: $count" # Correct output
undefined5. Array Operations
5. 数组操作
bash
undefinedbash
undefined❌ Incorrect array access
❌ Incorrect array access
arr=(1 2 3)
echo $arr[1] # Outputs 1[1]
arr=(1 2 3)
echo $arr[1] # Outputs 1[1]
✅ Correct array access
✅ Correct array access
echo ${arr[1]} # Outputs 2
echo ${arr[@]} # Outputs all elements
echo ${#arr[@]} # Outputs array length
undefinedecho ${arr[1]} # Outputs 2
echo ${arr[@]} # Outputs all elements
echo ${#arr[@]} # Outputs array length
undefined6. String Comparison
6. 字符串比较
bash
undefinedbash
undefined❌ Using = for string comparison
❌ Using = for string comparison
if [ $name = "John" ]; then # Not standard in some shells
if [ $name = "John" ]; then # Not standard in some shells
✅ Use = or ==
✅ Use = or ==
if [ "$name" = "John" ]; then
if [[ "$name" == "John" ]]; then
if [ "$name" = "John" ]; then
if [[ "$name" == "John" ]]; then
❌ Using -eq for numeric comparison instead of =
❌ Using -eq for numeric comparison instead of =
if [ $age = 18 ]; then # Wrong
if [ $age = 18 ]; then # Wrong
✅ Use arithmetic operators for numeric comparison
✅ Use arithmetic operators for numeric comparison
if [ $age -eq 18 ]; then
if (( age == 18 )); then
undefinedif [ $age -eq 18 ]; then
if (( age == 18 )); then
undefined7. Command Failure Continues Execution
7. 命令失败后继续执行
bash
undefinedbash
undefined❌ Execution continues after command failure
❌ Execution continues after command failure
cd /nonexistent
rm file.txt # Deletes file.txt in current directory
cd /nonexistent
rm file.txt # Deletes file.txt in current directory
✅ Use set -e to exit on error
✅ Use set -e to exit on error
set -e # or set -o errexit
cd /nonexistent # Script exits here
rm file.txt
set -e # or set -o errexit
cd /nonexistent # Script exits here
rm file.txt
Or check if command succeeded
Or check if command succeeded
cd /nonexistent || exit 1
undefinedcd /nonexistent || exit 1
undefinedCommon Debugging Commands
常用调试命令
Python pdb Debugger
Python pdb Debugger
Node.js Inspector
Node.js Inspector
Git Bisect
Git Bisect
Bash Debugging
Bash调试
bash
undefinedbash
undefinedRun script in debug mode
Run script in debug mode
bash -x script.sh # Print each command
bash -v script.sh # Print command source
bash -n script.sh # Syntax check, no execution
bash -x script.sh # Print each command
bash -v script.sh # Print command source
bash -n script.sh # Syntax check, no execution
Enable debugging within a script
Enable debugging within a script
set -x # Enable command tracing
set -v # Enable verbose mode
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Fail if any command in pipe fails
undefinedset -x # Enable command tracing
set -v # Enable verbose mode
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Fail if any command in pipe fails
undefinedPreventive Debugging
预防性调试
1. Use Type Checking
1. 使用类型检查
2. Input Validation
2. 输入校验
3. Defensive Programming
3. 防御式编程
4. Logging
4. 日志记录
Debugging Checklist
调试检查清单
Before Starting
开始前
- Obtain the complete error message
- Record the stack trace of the error
- Confirm reproduction steps
- Understand expected behavior
- 已获取完整的错误信息
- 已记录错误的栈轨迹
- 已确认复现步骤
- 已理解预期行为
During Debugging
调试中
- Check recent code changes
- Use binary search to locate the issue
- Add logs to trace variables
- Verify hypotheses
- 检查最近的代码变更
- 使用二分法定位问题
- 添加日志追踪变量
- 验证假设是否成立
After Resolution
解决后
- Confirm the original error is fixed
- Test related functionality
- Add tests to prevent regression
- Document the problem and solution
- 确认原始错误已修复
- 测试相关功能
- 新增测试用例防止回归
- 记录问题和解决方案
Additional Resources
额外资源
Reference Files
参考文件
For detailed debugging techniques and patterns:
- - Python error details
references/python-errors.md - - JavaScript/TypeScript error details
references/javascript-errors.md - - Bash/Zsh script error details
references/shell-errors.md - - Debugging tools usage guide
references/debugging-tools.md - - Common error patterns
references/common-patterns.md
如需了解详细的调试技术和模式:
- - Python错误详情
references/python-errors.md - - JavaScript/TypeScript错误详情
references/javascript-errors.md - - Bash/Zsh脚本错误详情
references/shell-errors.md - - 调试工具使用指南
references/debugging-tools.md - - 常见错误模式
references/common-patterns.md
Example Files
示例文件
Working debugging examples:
- - Complete debugging workflow example
examples/debugging-workflow.py - - Error handling patterns
examples/error-handling-patterns.py - - Shell script debugging example
examples/debugging-workflow.sh
可运行的调试示例:
- - 完整调试工作流示例
examples/debugging-workflow.py - - 错误处理模式
examples/error-handling-patterns.py - - Shell脚本调试示例
examples/debugging-workflow.sh