bug-detective

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bug 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:
  1. Understand the problem - Clearly define symptoms and expected behavior
  2. Gather evidence - Collect error messages, logs, stack traces
  3. Form hypotheses - Infer possible causes based on evidence
  4. Verify hypotheses - Confirm or eliminate causes through experiments
  5. Resolve the issue - Apply fixes and verify
调试是科学的问题解决过程,需要遵循以下步骤:
  1. 理解问题 - 明确定义问题症状和预期行为
  2. 收集证据 - 收集错误信息、日志、栈轨迹
  3. 提出假设 - 基于证据推断可能的原因
  4. 验证假设 - 通过实验确认或排除原因
  5. 解决问题 - 应用修复并验证效果

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 TypeCharacteristicsDebugging Method
Syntax ErrorCode cannot be parsedCheck syntax, bracket matching, quotes
Import ErrorModuleNotFoundErrorCheck module installation, path config
Type ErrorTypeErrorCheck data types, type conversions
Attribute ErrorAttributeErrorCheck if object attribute exists
Key ErrorKeyErrorCheck if dictionary key exists
Index ErrorIndexErrorCheck list/array index range
Null ReferenceNoneType/NullPointerExceptionCheck if variable is None
Network ErrorConnectionError/TimeoutCheck network connection, URL, timeout settings
Permission ErrorPermissionErrorCheck file permissions, user permissions
Resource ErrorFileNotFoundErrorCheck if file path exists
根据错误类型选择调试策略:
错误类型特征调试方法
Syntax Error代码无法被解析检查语法、括号匹配、引号
Import ErrorModuleNotFoundError检查模块安装情况、路径配置
Type ErrorTypeError检查数据类型、类型转换逻辑
Attribute ErrorAttributeError检查对象属性是否存在
Key ErrorKeyError检查字典键是否存在
Index ErrorIndexError检查列表/数组索引范围
Null ReferenceNoneType/NullPointerException检查变量是否为None
Network ErrorConnectionError/Timeout检查网络连接、URL、超时设置
Permission ErrorPermissionError检查文件权限、用户权限
Resource ErrorFileNotFoundError检查文件路径是否存在

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:
  1. The original error is resolved
  2. No new errors have been introduced
  3. Related functionality still works correctly
  4. Tests added to prevent regression
修复完成后,验证以下内容:
  1. 原始错误已解决
  2. 没有引入新的错误
  3. 相关功能仍然正常运行
  4. 新增测试用例防止回归

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

5. 使用
is
进行字符串比较

6. Forgetting to Call
super().__init__()

6. 忘记调用
super().__init__()

JavaScript/TypeScript Common Error Patterns

JavaScript/TypeScript常见错误模式

1.
this
Binding Issues

1.
this
绑定问题

2. Async Error Handling

2. 异步错误处理

3. Object Reference Comparison

3. 对象引用比较

Bash/Zsh Common Error Patterns

Bash/Zsh常见错误模式

1. Spacing Issues

1. 空格问题

bash
undefined
bash
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
undefined
if [ $name -eq 1 ]; then
undefined

2. Quoting Issues

2. 引号问题

bash
undefined
bash
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=
command
result=
command

✅ Use $()

✅ Use $()

result=$(command)
undefined
result=$(command)
undefined

3. Unquoted Variables

3. 未加引号的变量

bash
undefined
bash
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
undefined
set -u # or set -o nounset
undefined

4. Variable Scope in Loops

4. 循环中的变量作用域

bash
undefined
bash
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
undefined
while read line; do count=$((count + 1)) done < file.txt echo "Total: $count" # Correct output
undefined

5. Array Operations

5. 数组操作

bash
undefined
bash
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
undefined
echo ${arr[1]} # Outputs 2 echo ${arr[@]} # Outputs all elements echo ${#arr[@]} # Outputs array length
undefined

6. String Comparison

6. 字符串比较

bash
undefined
bash
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
undefined
if [ $age -eq 18 ]; then if (( age == 18 )); then
undefined

7. Command Failure Continues Execution

7. 命令失败后继续执行

bash
undefined
bash
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
undefined
cd /nonexistent || exit 1
undefined

Common Debugging Commands

常用调试命令

Python pdb Debugger

Python pdb Debugger

Node.js Inspector

Node.js Inspector

Git Bisect

Git Bisect

Bash Debugging

Bash调试

bash
undefined
bash
undefined

Run 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
undefined
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
undefined

Preventive 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:
  • references/python-errors.md
    - Python error details
  • references/javascript-errors.md
    - JavaScript/TypeScript error details
  • references/shell-errors.md
    - Bash/Zsh script error details
  • references/debugging-tools.md
    - Debugging tools usage guide
  • references/common-patterns.md
    - Common error patterns
如需了解详细的调试技术和模式:
  • references/python-errors.md
    - Python错误详情
  • references/javascript-errors.md
    - JavaScript/TypeScript错误详情
  • references/shell-errors.md
    - Bash/Zsh脚本错误详情
  • references/debugging-tools.md
    - 调试工具使用指南
  • references/common-patterns.md
    - 常见错误模式

Example Files

示例文件

Working debugging examples:
  • examples/debugging-workflow.py
    - Complete debugging workflow example
  • examples/error-handling-patterns.py
    - Error handling patterns
  • examples/debugging-workflow.sh
    - Shell script debugging example
可运行的调试示例:
  • examples/debugging-workflow.py
    - 完整调试工作流示例
  • examples/error-handling-patterns.py
    - 错误处理模式
  • examples/debugging-workflow.sh
    - Shell脚本调试示例