debugging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Resources

资源

scripts/
  validate-debugging.sh
references/
  debugging-patterns.md
scripts/
  validate-debugging.sh
references/
  debugging-patterns.md

Debugging Quality Skill

调试质量技能

This skill teaches you how to debug systematically using GoodVibes precision tools. Effective debugging requires a methodical approach: reproduce the issue, isolate the cause, identify the root problem, apply a fix, and verify the solution.
本技能将教你如何使用GoodVibes精准工具进行系统化调试。有效的调试需要遵循严谨的流程:复现问题、定位原因、识别根本问题、应用修复方案并验证解决方案。

When to Use This Skill

何时使用此技能

Load this skill when:
  • Investigating runtime errors or exceptions
  • Tracing unexpected behavior or logic errors
  • Analyzing network request/response issues
  • Debugging state management problems
  • Diagnosing performance bottlenecks
  • Investigating build or compilation errors
  • Understanding TypeScript type errors
  • Performing root cause analysis
Trigger phrases: "debug this error", "why is this failing", "investigate the issue", "trace the problem", "analyze the error".
在以下场景加载此技能:
  • 排查运行时错误或异常
  • 追踪异常行为或逻辑错误
  • 分析网络请求/响应问题
  • 调试状态管理问题
  • 诊断性能瓶颈
  • 排查构建或编译错误
  • 理解TypeScript类型错误
  • 执行根本原因分析
触发语句:"debug this error"、"why is this failing"、"investigate the issue"、"trace the problem"、"analyze the error"。

Core Workflow

核心流程

Phase 1: Reproduce - Confirm the Issue

阶段1:复现 - 确认问题

Before debugging, confirm you can reproduce the issue reliably.
在调试前,确认你能稳定复现问题。

Step 1.1: Gather Error Context

步骤1.1:收集错误上下文

Collect all available error information.
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1"
    - cmd: "npm run lint 2>&1"
    - cmd: "npm run build 2>&1"
  verbosity: standard
What to capture:
  • Complete error message and stack trace
  • Error type and code (if applicable)
  • File path and line number
  • Timestamps and environment info
  • User actions that triggered the error
收集所有可用的错误信息。
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1"
    - cmd: "npm run lint 2>&1"
    - cmd: "npm run build 2>&1"
  verbosity: standard
需要捕获的信息:
  • 完整的错误消息和堆栈跟踪
  • 错误类型和代码(如有)
  • 文件路径和行号
  • 时间戳和环境信息
  • 触发错误的用户操作

Step 1.2: Find Error Occurrences

步骤1.2:查找错误出现位置

Search for similar errors in the codebase.
yaml
discover:
  queries:
    - id: error_throw_sites
      type: grep
      pattern: "throw new (Error|TypeError|RangeError)"
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: error_handlers
      type: grep
      pattern: "catch\\s*\\("
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: console_errors
      type: grep
      pattern: "console\\.(error|warn)"
      glob: "**/*.{ts,tsx,js,jsx}"
  verbosity: locations
Pattern categories:
Error PatternMeaningCommon Causes
ReferenceErrorVariable not definedTypo, missing import, scope issue
TypeErrorWrong type usednull/undefined, wrong method, type mismatch
RangeErrorValue out of rangeArray index, numeric overflow
SyntaxErrorInvalid syntaxParsing error, malformed JSON
NetworkErrorRequest failedCORS, timeout, 404, auth failure
在代码库中搜索类似错误。
yaml
discover:
  queries:
    - id: error_throw_sites
      type: grep
      pattern: "throw new (Error|TypeError|RangeError)"
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: error_handlers
      type: grep
      pattern: "catch\\s*\\("
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: console_errors
      type: grep
      pattern: "console\\.(error|warn)"
      glob: "**/*.{ts,tsx,js,jsx}"
  verbosity: locations
错误模式分类:
错误模式含义常见原因
ReferenceError变量未定义拼写错误、缺少导入、作用域问题
TypeError使用了错误类型null/undefined、调用错误方法、类型不匹配
RangeError值超出范围数组索引、数值溢出
SyntaxError无效语法解析错误、格式错误的JSON
NetworkError请求失败CORS、超时、404、认证失败

Step 1.3: Reproduce Locally

步骤1.3:本地复现

Run the failing operation to confirm reproduction.
yaml
precision_exec:
  commands:
    - cmd: "npm run dev"
      timeout_ms: 5000
  verbosity: minimal
Reproduction checklist:
  • Error reproduces consistently
  • Minimal steps to reproduce identified
  • Environment matches production (Node version, deps)
  • Error message matches reported issue
执行失败的操作以确认问题可复现。
yaml
precision_exec:
  commands:
    - cmd: "npm run dev"
      timeout_ms: 5000
  verbosity: minimal
复现检查清单:
  • 错误可稳定复现
  • 已确定最小复现步骤
  • 环境与生产环境匹配(Node版本、依赖)
  • 错误消息与报告的问题一致

Phase 2: Isolate - Narrow Down the Cause

阶段2:隔离 - 缩小原因范围

Reduce the problem space to find where the error originates.
缩小问题范围以找到错误的起源。

Step 2.1: Read the Stack Trace

步骤2.1:分析堆栈跟踪

Analyze the call stack to understand execution flow.
Stack trace example:
TypeError: Cannot read property 'name' of undefined
    at getUserName (src/utils/user.ts:42:18)
    at UserProfile (src/components/UserProfile.tsx:15:22)
    at renderWithHooks (node_modules/react/cjs/react.development.js:1234)
Reading strategy:
  1. Start at the top - The actual error location
  2. Trace backwards - Follow the call chain
  3. Ignore node_modules - Focus on your code
  4. Find the entry point - Where did the bad data come from?
yaml
precision_read:
  files:
    - path: "src/utils/user.ts"
      extract: content
      range: {start: 35, end: 50}
    - path: "src/components/UserProfile.tsx"
      extract: content
      range: {start: 10, end: 25}
  verbosity: standard
分析调用栈以理解执行流程。
堆栈跟踪示例:
TypeError: Cannot read property 'name' of undefined
    at getUserName (src/utils/user.ts:42:18)
    at UserProfile (src/components/UserProfile.tsx:15:22)
    at renderWithHooks (node_modules/react/cjs/react.development.js:1234)
阅读策略:
  1. 从顶部开始 - 实际错误发生的位置
  2. 反向追踪 - 跟随调用链
  3. 忽略node_modules - 聚焦自己的代码
  4. 找到入口点 - 错误数据来自哪里?
yaml
precision_read:
  files:
    - path: "src/utils/user.ts"
      extract: content
      range: {start: 35, end: 50}
    - path: "src/components/UserProfile.tsx"
      extract: content
      range: {start: 10, end: 25}
  verbosity: standard

Step 2.2: Trace Data Flow

步骤2.2:追踪数据流

Follow the data from source to error point.
yaml
discover:
  queries:
    - id: function_calls
      type: grep
      pattern: "getUserName\\("
      glob: "**/*.{ts,tsx}"
    - id: data_sources
      type: grep
      pattern: "(fetch|axios|prisma).*user"
      glob: "**/*.{ts,tsx}"
    - id: prop_passing
      type: grep
      pattern: "user=\\{"
      glob: "**/*.tsx"
  verbosity: locations
Data flow analysis:
  • Where does the data originate? (API, database, props)
  • What transformations occur? (map, filter, destructure)
  • What assumptions are made? (not null, specific shape)
  • Where could it become undefined?
跟随数据从源头到错误发生点的路径。
yaml
discover:
  queries:
    - id: function_calls
      type: grep
      pattern: "getUserName\\("
      glob: "**/*.{ts,tsx}"
    - id: data_sources
      type: grep
      pattern: "(fetch|axios|prisma).*user"
      glob: "**/*.{ts,tsx}"
    - id: prop_passing
      type: grep
      pattern: "user=\\{"
      glob: "**/*.tsx"
  verbosity: locations
数据流分析要点:
  • 数据起源于何处?(API、数据库、props)
  • 经过了哪些转换?(map、filter、解构)
  • 做出了哪些假设?(非null、特定结构)
  • 在哪里可能变为undefined?

Step 2.3: Check Boundary Conditions

步骤2.3:检查边界条件

Test edge cases where errors commonly occur.
yaml
discover:
  queries:
    - id: array_access
      type: grep
      pattern: "\\[[0-9]+\\]|\\[.*\\]"
      glob: "**/*.{ts,tsx}"
    - id: null_checks
      type: grep
      pattern: "(if.*===.*null|if.*===.*undefined|\\?\\.|\\?\\?)"
      glob: "**/*.{ts,tsx}"
    - id: optional_chaining
      type: grep
      pattern: "\\?\\."
      glob: "**/*.{ts,tsx}"
  verbosity: locations
Common boundary issues:
IssueExampleFix
Array out of bounds
arr[arr.length]
Check
arr.length > 0
Null/undefined access
user.name
Use
user?.name
Division by zero
total / count
Check
count !== 0
Empty string operations
str[0]
Check
str.length > 0
Missing object keys
obj.key
Use
obj?.key ?? default
测试错误常发的边缘场景。
yaml
discover:
  queries:
    - id: array_access
      type: grep
      pattern: "\\[[0-9]+\\]|\\[.*\\]"
      glob: "**/*.{ts,tsx}"
    - id: null_checks
      type: grep
      pattern: "(if.*===.*null|if.*===.*undefined|\\?\\.|\\?\\?)"
      glob: "**/*.{ts,tsx}"
    - id: optional_chaining
      type: grep
      pattern: "\\?\\."
      glob: "**/*.{ts,tsx}"
  verbosity: locations
常见边界问题:
问题示例修复方案
数组越界
arr[arr.length]
检查
arr.length > 0
Null/undefined访问
user.name
使用
user?.name
除以零
total / count
检查
count !== 0
空字符串操作
str[0]
检查
str.length > 0
缺失对象键
obj.key
使用
obj?.key ?? default

Phase 3: Identify - Pinpoint the Root Cause

阶段3:识别 - 定位根本原因

Determine the underlying problem, not just the symptom.
确定潜在问题,而不仅仅是表面症状。

Step 3.1: Analyze Error Patterns

步骤3.1:分析错误模式

Classify the error to understand common causes.
Type Errors
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1 | head -50"
  verbosity: standard
Common TypeScript errors:
Error CodeMeaningFix
TS2339Property does not existAdd property to type or use optional chaining
TS2345Argument type mismatchFix the type or add type assertion
TS2322Type not assignableChange the type or fix the value
TS2571Object is of type unknownAdd type guard or assertion
TS7006Implicit any parameterAdd parameter type annotation
Runtime Errors
yaml
discover:
  queries:
    - id: unsafe_access
      type: grep
      pattern: "\\.[a-zA-Z]+(?!\\?)"
      glob: "**/*.{ts,tsx}"
    - id: async_errors
      type: grep
      pattern: "await.*(?!try)"
      glob: "**/*.{ts,tsx}"
  verbosity: files_only
Common runtime errors:
  • Cannot read property X of undefined
  • Cannot read property X of null
  • X is not a function
  • X is not iterable
  • Maximum call stack size exceeded (infinite recursion)
对错误进行分类以理解常见原因。
类型错误
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1 | head -50"
  verbosity: standard
常见TypeScript错误:
错误代码含义修复方案
TS2339属性不存在为类型添加属性或使用可选链
TS2345参数类型不匹配修复类型或添加类型断言
TS2322类型不可分配更改类型或修复值
TS2571对象类型为unknown添加类型守卫或断言
TS7006隐式any参数添加参数类型注解
运行时错误
yaml
discover:
  queries:
    - id: unsafe_access
      type: grep
      pattern: "\\.[a-zA-Z]+(?!\\?)"
      glob: "**/*.{ts,tsx}"
    - id: async_errors
      type: grep
      pattern: "await.*(?!try)"
      glob: "**/*.{ts,tsx}"
  verbosity: files_only
常见运行时错误:
  • Cannot read property X of undefined
  • Cannot read property X of null
  • X is not a function
  • X is not iterable
  • Maximum call stack size exceeded(无限递归)

Step 3.2: Check Dependencies and Imports

步骤3.2:检查依赖与导入

Module resolution errors are common.
yaml
discover:
  queries:
    - id: imports
      type: grep
      pattern: "^import.*from"
      glob: "**/*.{ts,tsx}"
    - id: dynamic_imports
      type: grep
      pattern: "import\\("
      glob: "**/*.{ts,tsx}"
    - id: require_statements
      type: grep
      pattern: "require\\("
      glob: "**/*.{ts,js}"
  verbosity: locations
Common import issues:
IssueSymptomFix
Missing exportModule has no exported memberAdd export to source file
Circular dependencyCannot access before initializationRestructure imports
Wrong pathModule not foundFix relative path or alias
Default vs namedX is not a functionUse
import X
or
import { X }
Type-only importCannot use as valueRemove
type
keyword
模块解析错误很常见。
yaml
discover:
  queries:
    - id: imports
      type: grep
      pattern: "^import.*from"
      glob: "**/*.{ts,tsx}"
    - id: dynamic_imports
      type: grep
      pattern: "import\\("
      glob: "**/*.{ts,tsx}"
    - id: require_statements
      type: grep
      pattern: "require\\("
      glob: "**/*.{ts,js}"
  verbosity: locations
常见导入问题:
问题症状修复方案
缺少导出Module has no exported member向源文件添加导出
循环依赖Cannot access before initialization重构导入结构
路径错误Module not found修复相对路径或别名
默认导出与命名导出混淆X is not a function使用
import X
import { X }
仅类型导入Cannot use as value移除
type
关键字

Step 3.3: Validate Assumptions

步骤3.3:验证假设

Question assumptions about data shape and state.
yaml
precision_grep:
  queries:
    - id: type_assertions
      pattern: "as (unknown|any|[A-Z][a-zA-Z]+)"
      glob: "**/*.{ts,tsx}"
  output:
    format: context
    context_before: 2
    context_after: 2
  verbosity: standard
Dangerous assumptions:
  • API always returns expected shape
  • Array is never empty
  • User is always authenticated
  • Data is always valid
  • Props are always provided
Validate with:
  • Runtime type validation (Zod, Yup)
  • Type guards (
    if (typeof x === 'string')
    )
  • Null checks (
    if (x != null)
    )
  • Default values (
    x ?? defaultValue
    )
质疑关于数据结构和状态的假设。
yaml
precision_grep:
  queries:
    - id: type_assertions
      pattern: "as (unknown|any|[A-Z][a-zA-Z]+)"
      glob: "**/*.{ts,tsx}"
  output:
    format: context
    context_before: 2
    context_after: 2
  verbosity: standard
危险的假设:
  • API始终返回预期结构
  • 数组永远不为空
  • 用户始终已认证
  • 数据始终有效
  • Props始终已提供
验证方式:
  • 运行时类型验证(Zod、Yup)
  • 类型守卫(
    if (typeof x === 'string')
  • Null检查(
    if (x != null)
  • 默认值(
    x ?? defaultValue

Phase 4: Fix - Apply the Solution

阶段4:修复 - 应用解决方案

Implement the fix based on root cause analysis.
根据根本原因分析实施修复。

Step 4.1: Choose the Right Fix

步骤4.1:选择合适的修复方案

Match the fix to the problem type.
Type Safety Fixes
typescript
// Before: Implicit any
function getUser(id) {
  return users.find(u => u.id === id);
}

// After: Explicit types
function getUser(id: string): User | undefined {
  return users.find(u => u.id === id);
}
Null Safety Fixes
typescript
// Before: Unsafe access
const name = user.profile.name;

// After: Optional chaining
const name = user?.profile?.name ?? 'Anonymous';
Async Error Handling
typescript
// Before: Unhandled promise
await fetchData();

// After: Try/catch
try {
  await fetchData();
} catch (error: unknown) {
  logger.error('Failed to fetch data', { error });
  throw new AppError('Data fetch failed', { cause: error });
}
Array Boundary Fixes
typescript
// Before: Unsafe access
const first = items[0];

// After: Safe access
const first = items.length > 0 ? items[0] : null;
// Or: const first = items.at(0) ?? null;
根据问题类型匹配修复方案。
类型安全修复
typescript
// 之前:隐式any
function getUser(id) {
  return users.find(u => u.id === id);
}

// 之后:显式类型
function getUser(id: string): User | undefined {
  return users.find(u => u.id === id);
}
Null安全修复
typescript
// 之前:不安全访问
const name = user.profile.name;

// 之后:可选链
const name = user?.profile?.name ?? 'Anonymous';
异步错误处理
typescript
// 之前:未处理的Promise
await fetchData();

// 之后:Try/catch
try {
  await fetchData();
} catch (error: unknown) {
  logger.error('Failed to fetch data', { error });
  throw new AppError('Data fetch failed', { cause: error });
}
数组边界修复
typescript
// 之前:不安全访问
const first = items[0];

// 之后:安全访问
const first = items.length > 0 ? items[0] : null;
// 或者:const first = items.at(0) ?? null;

Step 4.2: Add Defensive Code

步骤4.2:添加防御性代码

Prevent similar errors in the future.
Input validation:
typescript
import { z } from 'zod';

const userSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

function processUser(data: unknown) {
  const user = userSchema.parse(data); // Throws if invalid
  // Now user is type-safe
}
Type guards:
typescript
function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    'email' in value
  );
}

if (isUser(data)) {
  // TypeScript knows data is User
  logger.info('User email', { email: data.email });
}
Error boundaries (React):
typescript
import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error }: { error: Error }) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary FallbackComponent={ErrorFallback}>
  <MyComponent />
</ErrorBoundary>
防止未来出现类似错误。
输入验证:
typescript
import { z } from 'zod';

const userSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

function processUser(data: unknown) {
  const user = userSchema.parse(data); // 无效时抛出错误
  // 现在user是类型安全的
}
类型守卫:
typescript
function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    'email' in value
  );
}

if (isUser(data)) {
  // TypeScript知道data是User类型
  logger.info('User email', { email: data.email });
}
错误边界(React):
typescript
import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error }: { error: Error }) {
  return (
    <div role="alert">
      <p>出现错误:</p>
      <pre>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary FallbackComponent={ErrorFallback}>
  <MyComponent />
</ErrorBoundary>

Step 4.3: Apply the Fix

步骤4.3:应用修复

Use precision_edit to make the change.
yaml
precision_edit:
  edits:
    - path: "src/utils/user.ts"
      find: |
        function getUserName(user) {
          return user.name;
        }
      replace: |
        function getUserName(user: User | undefined): string {
          return user?.name ?? 'Unknown';
        }
  verbosity: minimal
使用precision_edit进行修改。
yaml
precision_edit:
  edits:
    - path: "src/utils/user.ts"
      find: |
        function getUserName(user) {
          return user.name;
        }
      replace: |
        function getUserName(user: User | undefined): string {
          return user?.name ?? 'Unknown';
        }
  verbosity: minimal

Phase 5: Verify - Confirm the Fix Works

阶段5:验证 - 确认修复有效

Validate that the fix resolves the issue without breaking anything.
验证修复解决了问题且未引入新问题。

Step 5.1: Type Check

步骤5.1:类型检查

Ensure TypeScript errors are resolved.
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck"
  verbosity: standard
All type errors must be resolved.
确保TypeScript错误已解决。
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck"
  verbosity: standard
所有类型错误必须解决。

Step 5.2: Run Tests

步骤5.2:运行测试

Confirm tests pass.
yaml
precision_exec:
  commands:
    - cmd: "npm test"
  verbosity: standard
If tests fail:
  • Fix introduced a regression
  • Test expectations need updating
  • Test revealed another issue
确认测试通过。
yaml
precision_exec:
  commands:
    - cmd: "npm test"
  verbosity: standard
如果测试失败:
  • 修复引入了回归问题
  • 测试预期需要更新
  • 测试揭示了另一个问题

Step 5.3: Manual Verification

步骤5.3:手动验证

Reproduce the original error scenario.
yaml
precision_exec:
  commands:
    - cmd: "npm run dev"
      timeout_ms: 5000
  verbosity: minimal
Verification checklist:
  • Original error no longer occurs
  • Edge cases handled (null, empty, large values)
  • No new errors introduced
  • Performance not degraded
  • User experience improved
复现原始错误场景。
yaml
precision_exec:
  commands:
    - cmd: "npm run dev"
      timeout_ms: 5000
  verbosity: minimal
验证检查清单:
  • 原始错误不再出现
  • 边缘场景已处理(null、空值、大值)
  • 未引入新错误
  • 性能未下降
  • 用户体验得到改善

Phase 6: Network Debugging

阶段6:网络调试

Debug API requests and responses.
调试API请求和响应。

Step 6.1: Find Network Calls

步骤6.1:查找网络调用

Locate all HTTP requests.
yaml
discover:
  queries:
    - id: fetch_calls
      type: grep
      pattern: "fetch\\("
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: axios_calls
      type: grep
      pattern: "axios\\.(get|post|put|delete|patch)"
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: api_routes
      type: glob
      patterns: ["src/app/api/**/*.ts", "pages/api/**/*.ts"]
  verbosity: locations
定位所有HTTP请求。
yaml
discover:
  queries:
    - id: fetch_calls
      type: grep
      pattern: "fetch\\("
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: axios_calls
      type: grep
      pattern: "axios\\.(get|post|put|delete|patch)"
      glob: "**/*.{ts,tsx,js,jsx}"
    - id: api_routes
      type: glob
      patterns: ["src/app/api/**/*.ts", "pages/api/**/*.ts"]
  verbosity: locations

Step 6.2: Check Request/Response Handling

步骤6.2:检查请求/响应处理

Validate error handling for network calls.
yaml
precision_grep:
  queries:
    - id: fetch_with_catch
      pattern: "fetch\\([^)]+\\).*catch"
      glob: "**/*.{ts,tsx,js,jsx}"
  output:
    format: context
    context_after: 5
  verbosity: standard
Common network issues:
IssueSymptomFix
CORS errorBlocked by CORS policyAdd CORS headers to API
401 UnauthorizedMissing or invalid tokenAdd auth header, refresh token
404 Not FoundWrong URL or routeFix endpoint path
500 Server ErrorBackend exceptionCheck server logs, fix backend
TimeoutRequest takes too longIncrease timeout, optimize backend
Network failureFailed to fetchCheck connectivity, retry logic
Debugging CORS:
typescript
// Next.js API route
export async function GET(request: Request) {
  return Response.json(data, {
    headers: {
      'Access-Control-Allow-Origin': '*', // Development only - use specific origin in production
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  });
}
Debugging authentication:
typescript
// Check for auth header
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
if (!token) {
  return Response.json({ error: 'Unauthorized' }, { status: 401 });
}

try {
  const session = await verifyToken(token);
} catch (error: unknown) {
  logger.error('Token verification failed', { error });
  return Response.json({ error: 'Invalid token' }, { status: 401 });
}
验证网络调用的错误处理。
yaml
precision_grep:
  queries:
    - id: fetch_with_catch
      pattern: "fetch\\([^)]+\\).*catch"
      glob: "**/*.{ts,tsx,js,jsx}"
  output:
    format: context
    context_after: 5
  verbosity: standard
常见网络问题:
问题症状修复方案
CORS错误Blocked by CORS policy为API添加CORS头
401 Unauthorized令牌缺失或无效添加认证头、刷新令牌
404 Not FoundURL或路由错误修复端点路径
500 Server Error后端异常检查服务器日志、修复后端
超时请求耗时过长增加超时时间、优化后端
网络故障Failed to fetch检查连接性、添加重试逻辑
调试CORS:
typescript
// Next.js API路由
export async function GET(request: Request) {
  return Response.json(data, {
    headers: {
      'Access-Control-Allow-Origin': '*', // 仅开发环境使用 - 生产环境使用特定源
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  });
}
调试认证:
typescript
// 检查认证头
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
if (!token) {
  return Response.json({ error: 'Unauthorized' }, { status: 401 });
}

try {
  const session = await verifyToken(token);
} catch (error: unknown) {
  logger.error('Token verification failed', { error });
  return Response.json({ error: 'Invalid token' }, { status: 401 });
}

Step 6.3: Validate Request Payloads

步骤6.3:验证请求负载

Ensure request data is correct.
yaml
discover:
  queries:
    - id: request_bodies
      type: grep
      pattern: "(body:|JSON.stringify)"
      glob: "**/*.{ts,tsx}"
    - id: validation_schemas
      type: grep
      pattern: "z\\.object\\("
      glob: "**/*.{ts,tsx}"
  verbosity: locations
Request validation:
typescript
import { z } from 'zod';

const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

export async function POST(request: Request) {
  const body = await request.json();
  const result = createUserSchema.safeParse(body);
  
  if (!result.success) {
    return Response.json(
      { error: 'Validation failed', details: result.error.flatten() },
      { status: 400 }
    );
  }
  
  // Now result.data is type-safe
}
确保请求数据正确。
yaml
discover:
  queries:
    - id: request_bodies
      type: grep
      pattern: "(body:|JSON.stringify)"
      glob: "**/*.{ts,tsx}"
    - id: validation_schemas
      type: grep
      pattern: "z\\.object\\("
      glob: "**/*.{ts,tsx}"
  verbosity: locations
请求验证:
typescript
import { z } from 'zod';

const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

export async function POST(request: Request) {
  const body = await request.json();
  const result = createUserSchema.safeParse(body);
  
  if (!result.success) {
    return Response.json(
      { error: 'Validation failed', details: result.error.flatten() },
      { status: 400 }
    );
  }
  
  // 现在result.data是类型安全的
}

Phase 7: State Debugging

阶段7:状态调试

Debug React state and state management.
调试React状态和状态管理。

Step 7.1: Find State Usage

步骤7.1:查找状态使用情况

Locate state declarations and updates.
yaml
discover:
  queries:
    - id: useState_calls
      type: grep
      pattern: "useState<?"
      glob: "**/*.{tsx,jsx}"
    - id: state_updates
      type: grep
      pattern: "set[A-Z][a-zA-Z]*\\("
      glob: "**/*.{tsx,jsx}"
    - id: useEffect_hooks
      type: grep
      pattern: "useEffect\\("
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
Common state issues:
IssueSymptomFix
Stale closureState value is outdatedUse functional update
Missing dependencyuseEffect doesn't re-runAdd to dependency array
Infinite loopComponent re-renders foreverFix dependencies or condition
State race conditionUpdates override each otherUse reducer or queue
Lost state on unmountData disappearsLift state up or use global state
Stale closure fix:
typescript
// Before: Stale closure
const [count, setCount] = useState(0);

function increment() {
  setTimeout(() => {
    setCount(count + 1); // count is stale
  }, 1000);
}

// After: Functional update
function increment() {
  setTimeout(() => {
    setCount(prev => prev + 1); // Always current
  }, 1000);
}
useEffect dependency fix:
typescript
// Before: Missing dependency
useEffect(() => {
  fetchData(userId);
}, []); // userId changes ignored

// After: Complete dependencies
useEffect(() => {
  fetchData(userId);
}, [userId]); // Re-runs when userId changes
定位状态声明和更新。
yaml
discover:
  queries:
    - id: useState_calls
      type: grep
      pattern: "useState<?"
      glob: "**/*.{tsx,jsx}"
    - id: state_updates
      type: grep
      pattern: "set[A-Z][a-zA-Z]*\\("
      glob: "**/*.{tsx,jsx}"
    - id: useEffect_hooks
      type: grep
      pattern: "useEffect\\("
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
常见状态问题:
问题症状修复方案
陈旧闭包状态值过时使用函数式更新
缺失依赖useEffect未重新运行添加到依赖数组
无限循环组件无限重渲染修复依赖或条件
状态竞态条件更新相互覆盖使用reducer或队列
卸载后丢失状态数据消失提升状态或使用全局状态
陈旧闭包修复:
typescript
// 之前:陈旧闭包
const [count, setCount] = useState(0);

function increment() {
  setTimeout(() => {
    setCount(count + 1); // count是陈旧的
  }, 1000);
}

// 之后:函数式更新
function increment() {
  setTimeout(() => {
    setCount(prev => prev + 1); // 始终获取当前值
  }, 1000);
}
useEffect依赖修复:
typescript
// 之前:缺失依赖
useEffect(() => {
  fetchData(userId);
}, []); // userId变化时不会重新运行

// 之后:完整依赖
useEffect(() => {
  fetchData(userId);
}, [userId]); // userId变化时重新运行

Step 7.2: Check for State Mutations

步骤7.2:检查状态突变

Find direct state mutations (anti-pattern).
yaml
discover:
  queries:
    - id: array_mutations
      type: grep
      pattern: "\\.(push|pop|shift|unshift|splice)\\("
      glob: "**/*.{tsx,jsx}"
    - id: object_mutations
      type: grep
      pattern: "[a-zA-Z]+\\.[a-zA-Z]+\\s*=\\s*"
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
Immutable updates:
typescript
// Before: Mutation
const [items, setItems] = useState([1, 2, 3]);
items.push(4); // BAD: Mutates state
setItems(items);

// After: Immutable
setItems([...items, 4]); // GOOD: New array

// Object updates
const [user, setUser] = useState({ name: 'Alice', age: 30 });
setUser({ ...user, age: 31 }); // GOOD: New object
查找直接的状态突变(反模式)。
yaml
discover:
  queries:
    - id: array_mutations
      type: grep
      pattern: "\\.(push|pop|shift|unshift|splice)\\("
      glob: "**/*.{tsx,jsx}"
    - id: object_mutations
      type: grep
      pattern: "[a-zA-Z]+\\.[a-zA-Z]+\\s*=\\s*"
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
不可变更新:
typescript
// 之前:突变
const [items, setItems] = useState([1, 2, 3]);
items.push(4); // 错误:直接突变状态
setItems(items);

// 之后:不可变更新
setItems([...items, 4]); // 正确:新数组

// 对象更新
const [user, setUser] = useState({ name: 'Alice', age: 30 });
setUser({ ...user, age: 31 }); // 正确:新对象

Phase 8: Performance Debugging

阶段8:性能调试

Diagnose performance bottlenecks.
诊断性能瓶颈。

Step 8.1: Find Performance Anti-patterns

步骤8.1:查找性能反模式

Search for common performance issues.
yaml
discover:
  queries:
    - id: n_plus_one
      type: grep
      pattern: "(for|forEach|map).*await.*(prisma|db|query)"
      glob: "**/*.{ts,tsx}"
    - id: inline_objects
      type: grep
      pattern: "(onClick|onChange|style)=\\{\\{"
      glob: "**/*.{tsx,jsx}"
    - id: missing_memo
      type: grep
      pattern: "(map|filter|reduce|sort)\\("
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
Performance issues:
Anti-patternImpactFix
N+1 queriesSlow database queriesUse
include
or batch loading
Inline objects in JSXUnnecessary re-rendersExtract to constant or useMemo
Large lists without virtualizationSlow renderingUse react-window or similar
Missing indexesSlow queriesAdd database indexes
Unnecessary re-rendersLaggy UIUse React.memo, useMemo, useCallback
搜索常见的性能问题。
yaml
discover:
  queries:
    - id: n_plus_one
      type: grep
      pattern: "(for|forEach|map).*await.*(prisma|db|query)"
      glob: "**/*.{ts,tsx}"
    - id: inline_objects
      type: grep
      pattern: "(onClick|onChange|style)=\\{\\{"
      glob: "**/*.{tsx,jsx}"
    - id: missing_memo
      type: grep
      pattern: "(map|filter|reduce|sort)\\("
      glob: "**/*.{tsx,jsx}"
  verbosity: locations
性能问题:
反模式影响修复方案
N+1查询数据库查询缓慢使用
include
或批量加载
JSX中的内联对象不必要的重渲染提取为常量或使用useMemo
无虚拟化的大型列表渲染缓慢使用react-window等库
缺失索引查询缓慢添加数据库索引
不必要的重渲染UI卡顿使用React.memo、useMemo、useCallback

Step 8.2: Profile Build Performance

步骤8.2:分析构建性能

Check for slow builds.
yaml
precision_exec:
  commands:
    - cmd: "npm run build"
  verbosity: standard
Build performance issues:
  • Large bundle size (check with bundle analyzer)
  • Slow TypeScript compilation (check tsconfig)
  • Missing tree-shaking (check imports)
  • Development dependencies in production (check package.json)
检查缓慢的构建过程。
yaml
precision_exec:
  commands:
    - cmd: "npm run build"
  verbosity: standard
构建性能问题:
  • 包体积过大(使用包分析工具检查)
  • TypeScript编译缓慢(检查tsconfig)
  • 缺失摇树优化(检查导入)
  • 生产环境包含开发依赖(检查package.json)

Phase 9: Root Cause Analysis

阶段9:根本原因分析

Go beyond symptoms to find underlying issues.
超越表面症状,找到潜在问题。

Step 9.1: Ask Why Five Times

步骤9.1:五次追问为什么

Drill down to the root cause.
Example:
  1. Why did the app crash? - User data was undefined
  2. Why was user data undefined? - API returned null
  3. Why did API return null? - Database query returned no rows
  4. Why were there no rows? - User ID was incorrect
  5. Why was user ID incorrect? - Route parameter parsing failed
Root cause: Route parameter parsing doesn't handle edge cases.
深入挖掘根本原因。
示例:
  1. 应用为什么崩溃? - 用户数据为undefined
  2. 用户数据为什么是undefined? - API返回null
  3. API为什么返回null? - 数据库查询未返回行
  4. 为什么没有查询到行? - 用户ID不正确
  5. 用户ID为什么不正确? - 路由参数解析失败
根本原因: 路由参数解析未处理边缘情况。

Step 9.2: Check System Dependencies

步骤9.2:检查系统依赖

Validate environment and dependencies.
yaml
precision_exec:
  commands:
    - cmd: "node --version"
    - cmd: "npm --version"
    - cmd: "npm list --depth=0"
  verbosity: minimal
Common dependency issues:
  • Version mismatch (package.json vs lockfile)
  • Peer dependency conflicts
  • Outdated packages with known bugs
  • Missing native dependencies
验证环境和依赖。
yaml
precision_exec:
  commands:
    - cmd: "node --version"
    - cmd: "npm --version"
    - cmd: "npm list --depth=0"
  verbosity: minimal
常见依赖问题:
  • 版本不匹配(package.json与lockfile)
  • 对等依赖冲突
  • 存在已知bug的过时包
  • 缺失原生依赖

Step 9.3: Review Recent Changes

步骤9.3:查看最近的变更

Find what changed before the error appeared.
yaml
precision_exec:
  commands:
    - cmd: "git log --oneline -10"
    - cmd: "git diff HEAD~5..HEAD"
  verbosity: standard
Git bisect for complex issues:
bash
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
查找错误出现前的变更。
yaml
precision_exec:
  commands:
    - cmd: "git log --oneline -10"
    - cmd: "git diff HEAD~5..HEAD"
  verbosity: standard
复杂问题使用Git bisect:
bash
git bisect start
git bisect bad HEAD
git bisect good v1.0.0

Test, then mark:

测试,然后标记:

git bisect good # or bad
git bisect good # 或 bad

Repeat until culprit commit found

重复直到找到问题提交

undefined
undefined

Phase 10: Prevention - Avoid Future Issues

阶段10:预防 - 避免未来问题

Add safeguards to prevent recurrence.
添加防护措施防止问题复发。

Step 10.1: Add Tests

步骤10.1:添加测试

Write tests that catch the error.
typescript
import { describe, it, expect } from 'vitest';

describe('getUserName', () => {
  it('should handle undefined user', () => {
    expect(getUserName(undefined)).toBe('Unknown');
  });
  
  it('should handle user without name', () => {
    expect(getUserName({ id: '123' })).toBe('Unknown');
  });
  
  it('should return user name', () => {
    expect(getUserName({ id: '123', name: 'Alice' })).toBe('Alice');
  });
});
编写能捕获该错误的测试。
typescript
import { describe, it, expect } from 'vitest';

describe('getUserName', () => {
  it('should handle undefined user', () => {
    expect(getUserName(undefined)).toBe('Unknown');
  });
  
  it('should handle user without name', () => {
    expect(getUserName({ id: '123' })).toBe('Unknown');
  });
  
  it('should return user name', () => {
    expect(getUserName({ id: '123', name: 'Alice' })).toBe('Alice');
  });
});

Step 10.2: Add Logging

步骤10.2:添加日志

Log key decision points for future debugging.
typescript
import { logger } from '@/lib/logger';

function processUser(user: User | undefined) {
  if (!user) {
    logger.warn('User is undefined in processUser');
    return null;
  }
  
  logger.info('Processing user', { userId: user.id });
  
  try {
    // Process user
  } catch (error: unknown) {
    logger.error('Failed to process user', { userId: user.id, error });
    throw error;
  }
}
Logging best practices:
  • Use structured logging (JSON)
  • Include context (user ID, request ID)
  • Use appropriate log levels (error, warn, info, debug)
  • Never log sensitive data (passwords, tokens)
  • Use correlation IDs to trace requests
为未来调试记录关键决策点。
typescript
import { logger } from '@/lib/logger';

function processUser(user: User | undefined) {
  if (!user) {
    logger.warn('User is undefined in processUser');
    return null;
  }
  
  logger.info('Processing user', { userId: user.id });
  
  try {
    // 处理用户
  } catch (error: unknown) {
    logger.error('Failed to process user', { userId: user.id, error });
    throw error;
  }
}
日志最佳实践:
  • 使用结构化日志(JSON)
  • 包含上下文(用户ID、请求ID)
  • 使用适当的日志级别(error、warn、info、debug)
  • 绝不记录敏感数据(密码、令牌)
  • 使用关联ID追踪请求

Step 10.3: Add Monitoring

步骤10.3:添加监控

Track errors in production.
Error tracking (Sentry, Rollbar):
typescript
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 0.1,
  beforeSend(event, hint) {
    // Filter sensitive data
    if (event.request) {
      delete event.request.cookies;
    }
    return event;
  },
});
Custom error classes:
typescript
export class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500,
    public context?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'AppError';
  }
}

throw new AppError('User not found', 'USER_NOT_FOUND', 404, { userId });
在生产环境中追踪错误。
错误追踪(Sentry、Rollbar):
typescript
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 0.1,
  beforeSend(event, hint) {
    // 过滤敏感数据
    if (event.request) {
      delete event.request.cookies;
    }
    return event;
  },
});
自定义错误类:
typescript
export class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500,
    public context?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'AppError';
  }
}

throw new AppError('User not found', 'USER_NOT_FOUND', 404, { userId });

Common Debugging Patterns

常见调试模式

See
references/debugging-patterns.md
for detailed patterns organized by category.
查看
references/debugging-patterns.md
获取按类别组织的详细模式。

Error Pattern Detection

错误模式检测

Use
discover
to find multiple error patterns at once.
yaml
discover:
  queries:
    # Type safety issues
    - { id: any_usage, type: grep, pattern: ':\\s*any', glob: '**/*.{ts,tsx}' }
    - { id: type_assertions, type: grep, pattern: 'as (any|unknown)', glob: '**/*.{ts,tsx}' }
    # Runtime safety
    - { id: unsafe_access, type: grep, pattern: '\\.[a-zA-Z]+(?!\\?)', glob: '**/*.{ts,tsx}' }
    - { id: unhandled_promises, type: grep, pattern: 'await.*(?!try)', glob: '**/*.{ts,tsx}' }
    # Performance
    - { id: n_plus_one, type: grep, pattern: 'for.*await.*prisma', glob: '**/*.{ts,tsx}' }
    - { id: inline_objects, type: grep, pattern: 'onClick=\\{\\{', glob: '**/*.{tsx,jsx}' }
  verbosity: locations
使用
discover
同时查找多种错误模式。
yaml
discover:
  queries:
    # 类型安全问题
    - { id: any_usage, type: grep, pattern: ':\\s*any', glob: '**/*.{ts,tsx}' }
    - { id: type_assertions, type: grep, pattern: 'as (any|unknown)', glob: '**/*.{ts,tsx}' }
    # 运行时安全
    - { id: unsafe_access, type: grep, pattern: '\\.[a-zA-Z]+(?!\\?)', glob: '**/*.{ts,tsx}' }
    - { id: unhandled_promises, type: grep, pattern: 'await.*(?!try)', glob: '**/*.{ts,tsx}' }
    # 性能
    - { id: n_plus_one, type: grep, pattern: 'for.*await.*prisma', glob: '**/*.{ts,tsx}' }
    - { id: inline_objects, type: grep, pattern: 'onClick=\\{\\{', glob: '**/*.{tsx,jsx}' }
  verbosity: locations

Systematic Error Analysis

系统化错误分析

Step 1: Categorize the error
  • Type error (compile-time)
  • Runtime error (null, undefined, type mismatch)
  • Logic error (wrong behavior, no exception)
  • Performance error (too slow)
  • Network error (API failure)
Step 2: Find similar patterns
  • Search for the error message
  • Search for the error type
  • Search for the failing function name
Step 3: Trace the data
  • Where does the data come from?
  • What transformations occur?
  • Where does it fail?
Step 4: Validate assumptions
  • Is the data shape correct?
  • Are types accurate?
  • Are edge cases handled?
Step 5: Fix and verify
  • Apply the fix
  • Run type check
  • Run tests
  • Verify manually
步骤1:对错误分类
  • 类型错误(编译时)
  • 运行时错误(null、undefined、类型不匹配)
  • 逻辑错误(行为错误,无异常)
  • 性能错误(过慢)
  • 网络错误(API失败)
步骤2:查找类似模式
  • 搜索错误消息
  • 搜索错误类型
  • 搜索失败的函数名
步骤3:追踪数据
  • 数据来自哪里?
  • 经过了哪些转换?
  • 在哪里失败?
步骤4:验证假设
  • 数据结构是否正确?
  • 类型是否准确?
  • 边缘情况是否已处理?
步骤5:修复并验证
  • 应用修复
  • 运行类型检查
  • 运行测试
  • 手动验证

Precision Tools for Debugging

调试用精准工具

Discover Tool

Discover工具

Run parallel searches to find error patterns.
yaml
discover:
  queries:
    - id: error_sites
      type: grep
      pattern: "throw new"
      glob: '**/*.{ts,tsx,js,jsx}'
    - id: catch_blocks
      type: grep
      pattern: "catch\\s*\\("
      glob: '**/*.{ts,tsx,js,jsx}'
    - id: console_logs
      type: grep
      pattern: "console\\.(log|error|warn)"
      glob: '**/*.{ts,tsx,js,jsx}'
  verbosity: locations
运行并行搜索查找错误模式。
yaml
discover:
  queries:
    - id: error_sites
      type: grep
      pattern: "throw new"
      glob: '**/*.{ts,tsx,js,jsx}'
    - id: catch_blocks
      type: grep
      pattern: "catch\\s*\\("
      glob: '**/*.{ts,tsx,js,jsx}'
    - id: console_logs
      type: grep
      pattern: "console\\.(log|error|warn)"
      glob: '**/*.{ts,tsx,js,jsx}'
  verbosity: locations

Precision Grep

Precision Grep

Search with context for understanding surrounding code.
yaml
precision_grep:
  queries:
    - id: error_context
      pattern: "TypeError|ReferenceError|RangeError"
      glob: "**/*.{ts,tsx,js,jsx}"
  output:
    format: context
    context_before: 5
    context_after: 5
  verbosity: standard
带上下文搜索以理解周边代码。
yaml
precision_grep:
  queries:
    - id: error_context
      pattern: "TypeError|ReferenceError|RangeError"
      glob: "**/*.{ts,tsx,js,jsx}"
  output:
    format: context
    context_before: 5
    context_after: 5
  verbosity: standard

Precision Exec

Precision Exec

Run diagnostic commands.
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1"
    - cmd: "npm run lint 2>&1"
    - cmd: "npm test 2>&1"
  verbosity: standard
运行诊断命令。
yaml
precision_exec:
  commands:
    - cmd: "npm run typecheck 2>&1"
    - cmd: "npm run lint 2>&1"
    - cmd: "npm test 2>&1"
  verbosity: standard

Precision Edit

Precision Edit

Apply fixes atomically.
yaml
precision_edit:
  edits:
    - path: "src/utils/user.ts"
      find: "user.name"
      replace: "user?.name ?? 'Unknown'"
  verbosity: minimal
原子化应用修复。
yaml
precision_edit:
  edits:
    - path: "src/utils/user.ts"
      find: "user.name"
      replace: "user?.name ?? 'Unknown'"
  verbosity: minimal

Validation Script

验证脚本

Use
scripts/validate-debugging.sh
to validate debugging practices.
bash
./scripts/validate-debugging.sh /path/to/project
The script checks:
  • console.log statements removed from production
  • Error boundaries implemented
  • Source maps configured
  • Proper logging libraries used
  • Try/catch blocks handling errors
  • Debug dependencies excluded from production
使用
scripts/validate-debugging.sh
验证调试实践。
bash
./scripts/validate-debugging.sh /path/to/project
脚本检查内容:
  • 生产环境中已移除console.log语句
  • 已实现错误边界
  • 已配置源映射
  • 使用了合适的日志库
  • Try/catch块已处理错误
  • 调试依赖已排除在生产环境外

Quick Reference

快速参考

Debugging Checklist

调试检查清单

Reproduce:
  • Error reproduces consistently
  • Minimal reproduction steps identified
  • Environment matches
  • Error message captured
Isolate:
  • Stack trace analyzed
  • Data flow traced
  • Boundary conditions tested
  • Similar patterns found
Identify:
  • Error categorized
  • Root cause identified (not symptom)
  • Assumptions validated
  • Dependencies checked
Fix:
  • Appropriate fix chosen
  • Defensive code added
  • Fix applied
  • No new issues introduced
Verify:
  • Type check passes
  • Tests pass
  • Manual verification complete
  • Edge cases tested
Prevent:
  • Tests added for the issue
  • Logging added
  • Monitoring configured
  • Documentation updated
复现:
  • 错误可稳定复现
  • 已确定最小复现步骤
  • 环境匹配
  • 已捕获错误消息
隔离:
  • 已分析堆栈跟踪
  • 已追踪数据流
  • 已测试边界条件
  • 已找到类似模式
识别:
  • 已对错误分类
  • 已识别根本原因(而非症状)
  • 已验证假设
  • 已检查依赖
修复:
  • 已选择合适的修复方案
  • 已添加防御性代码
  • 已应用修复
  • 未引入新问题
验证:
  • 类型检查通过
  • 测试通过
  • 手动验证完成
  • 边缘场景已测试
预防:
  • 已为该问题添加测试
  • 已添加日志
  • 已配置监控
  • 已更新文档

Error Severity Guide

错误严重程度指南

Critical (fix immediately):
  • Application crashes
  • Data loss or corruption
  • Security vulnerabilities
  • Production outage
High (fix soon):
  • Feature completely broken
  • Poor user experience
  • Performance degradation
  • Type safety violations
Medium (fix when able):
  • Edge case failures
  • Minor UX issues
  • Console warnings
  • Missing error handling
Low (fix eventually):
  • Code style issues
  • Missing documentation
  • Optimization opportunities
  • Refactoring needs
严重(立即修复):
  • 应用崩溃
  • 数据丢失或损坏
  • 安全漏洞
  • 生产环境宕机
高优先级(尽快修复):
  • 功能完全失效
  • 用户体验极差
  • 性能下降
  • 类型安全违规
中优先级(有空时修复):
  • 边缘场景失败
  • 轻微UX问题
  • 控制台警告
  • 缺失错误处理
低优先级(最终修复):
  • 代码风格问题
  • 缺失文档
  • 优化机会
  • 重构需求

Common Mistakes to Avoid

需避免的常见错误

Fixing symptoms, not causes:
  • BAD: Add null check without understanding why it's null
  • GOOD: Trace why the value is null and fix the source
Skipping verification:
  • BAD: Apply fix and assume it works
  • GOOD: Run tests, type check, and manual verification
Ignoring edge cases:
  • BAD: Fix the common case only
  • GOOD: Test null, undefined, empty, and large values
No prevention:
  • BAD: Fix the bug and move on
  • GOOD: Add tests and logging to prevent recurrence
修复症状而非原因:
  • 错误:添加null检查但不理解为什么为null
  • 正确:追踪值为null的原因并修复源头
跳过验证:
  • 错误:应用修复后假设其有效
  • 正确:运行测试、类型检查和手动验证
忽略边缘场景:
  • 错误:仅修复常见场景
  • 正确:测试null、undefined、空值和大值
不做预防:
  • 错误:修复bug后继续开发
  • 正确:添加测试和日志防止复发

Advanced Techniques

高级技巧

Binary Search Debugging

二分查找调试

For complex issues, use binary search to narrow down.
Comment out half the code:
  1. Comment out half the function
  2. If error persists, problem is in remaining half
  3. If error disappears, problem is in commented half
  4. Repeat until isolated
对于复杂问题,使用二分查找缩小范围。
注释掉一半代码:
  1. 注释掉函数的一半
  2. 如果错误仍然存在,问题在剩余部分
  3. 如果错误消失,问题在注释部分
  4. 重复直到定位问题

Rubber Duck Debugging

橡皮鸭调试

Explain the problem out loud:
  1. Describe what the code should do
  2. Describe what it actually does
  3. Walk through line by line
  4. Often reveals the issue during explanation
大声解释问题:
  1. 描述代码应该做什么
  2. 描述代码实际做什么
  3. 逐行走查
  4. 通常在解释过程中就能发现问题

Time-Travel Debugging

时光旅行调试

Use git to find when the bug was introduced:
bash
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
使用Git查找bug引入的时间:
bash
git bisect start
git bisect bad HEAD
git bisect good v1.0.0

Test each commit

测试每个提交

git bisect good # or bad
undefined
git bisect good # 或 bad
undefined

Logging Strategy

日志策略

Trace important values:
typescript
function processData(data: unknown) {
  logger.debug('Input data', { data });
  
  const validated = schema.parse(data);
  logger.debug('Validated data', { validated });
  
  const transformed = transform(validated);
  logger.debug('Transformed data', { transformed });
  
  return transformed;
}
Use correlation IDs:
typescript
import { v4 as uuid } from 'uuid';

export async function POST(request: Request) {
  const requestId = uuid();
  logger.info('Request started', { requestId });
  
  try {
    const result = await processRequest(request);
    logger.info('Request completed', { requestId });
    return Response.json(result);
  } catch (error: unknown) {
    logger.error('Request failed', { requestId, error });
    throw error;
  }
}
追踪重要值:
typescript
function processData(data: unknown) {
  logger.debug('Input data', { data });
  
  const validated = schema.parse(data);
  logger.debug('Validated data', { validated });
  
  const transformed = transform(validated);
  logger.debug('Transformed data', { transformed });
  
  return transformed;
}
使用关联ID:
typescript
import { v4 as uuid } from 'uuid';

export async function POST(request: Request) {
  const requestId = uuid();
  logger.info('Request started', { requestId });
  
  try {
    const result = await processRequest(request);
    logger.info('Request completed', { requestId });
    return Response.json(result);
  } catch (error: unknown) {
    logger.error('Request failed', { requestId, error });
    throw error;
  }
}

Integration with Other Skills

与其他技能的集成

  • Use error-recovery for automated fix attempts
  • Use code-review to catch errors during review
  • Use testing-strategy to prevent regressions
  • Use performance-audit for performance issues
  • Use security-audit for security vulnerabilities
  • 使用error-recovery尝试自动修复
  • 使用code-review在代码审查时发现错误
  • 使用testing-strategy防止回归
  • 使用performance-audit处理性能问题
  • 使用security-audit处理安全漏洞

Resources

资源