debugging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseResources
资源
scripts/
validate-debugging.sh
references/
debugging-patterns.mdscripts/
validate-debugging.sh
references/
debugging-patterns.mdDebugging 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: standardWhat 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: locationsPattern categories:
| Error Pattern | Meaning | Common Causes |
|---|---|---|
| ReferenceError | Variable not defined | Typo, missing import, scope issue |
| TypeError | Wrong type used | null/undefined, wrong method, type mismatch |
| RangeError | Value out of range | Array index, numeric overflow |
| SyntaxError | Invalid syntax | Parsing error, malformed JSON |
| NetworkError | Request failed | CORS, 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: minimalReproduction 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:
- Start at the top - The actual error location
- Trace backwards - Follow the call chain
- Ignore node_modules - Focus on your code
- 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)阅读策略:
- 从顶部开始 - 实际错误发生的位置
- 反向追踪 - 跟随调用链
- 忽略node_modules - 聚焦自己的代码
- 找到入口点 - 错误数据来自哪里?
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: standardStep 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: locationsData 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: locationsCommon boundary issues:
| Issue | Example | Fix |
|---|---|---|
| Array out of bounds | | Check |
| Null/undefined access | | Use |
| Division by zero | | Check |
| Empty string operations | | Check |
| Missing object keys | | Use |
测试错误常发的边缘场景。
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常见边界问题:
| 问题 | 示例 | 修复方案 |
|---|---|---|
| 数组越界 | | 检查 |
| Null/undefined访问 | | 使用 |
| 除以零 | | 检查 |
| 空字符串操作 | | 检查 |
| 缺失对象键 | | 使用 |
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: standardCommon TypeScript errors:
| Error Code | Meaning | Fix |
|---|---|---|
| TS2339 | Property does not exist | Add property to type or use optional chaining |
| TS2345 | Argument type mismatch | Fix the type or add type assertion |
| TS2322 | Type not assignable | Change the type or fix the value |
| TS2571 | Object is of type unknown | Add type guard or assertion |
| TS7006 | Implicit any parameter | Add 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_onlyCommon 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: locationsCommon import issues:
| Issue | Symptom | Fix |
|---|---|---|
| Missing export | Module has no exported member | Add export to source file |
| Circular dependency | Cannot access before initialization | Restructure imports |
| Wrong path | Module not found | Fix relative path or alias |
| Default vs named | X is not a function | Use |
| Type-only import | Cannot use as value | Remove |
模块解析错误很常见。
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 | 使用 |
| 仅类型导入 | Cannot use as value | 移除 |
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: standardDangerous 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: minimalPhase 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: standardAll 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: standardIf 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: minimalVerification 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: locationsStep 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: standardCommon network issues:
| Issue | Symptom | Fix |
|---|---|---|
| CORS error | Blocked by CORS policy | Add CORS headers to API |
| 401 Unauthorized | Missing or invalid token | Add auth header, refresh token |
| 404 Not Found | Wrong URL or route | Fix endpoint path |
| 500 Server Error | Backend exception | Check server logs, fix backend |
| Timeout | Request takes too long | Increase timeout, optimize backend |
| Network failure | Failed to fetch | Check 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 Found | URL或路由错误 | 修复端点路径 |
| 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: locationsRequest 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: locationsCommon state issues:
| Issue | Symptom | Fix |
|---|---|---|
| Stale closure | State value is outdated | Use functional update |
| Missing dependency | useEffect doesn't re-run | Add to dependency array |
| Infinite loop | Component re-renders forever | Fix dependencies or condition |
| State race condition | Updates override each other | Use reducer or queue |
| Lost state on unmount | Data disappears | Lift 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: locationsImmutable 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: locationsPerformance issues:
| Anti-pattern | Impact | Fix |
|---|---|---|
| N+1 queries | Slow database queries | Use |
| Inline objects in JSX | Unnecessary re-renders | Extract to constant or useMemo |
| Large lists without virtualization | Slow rendering | Use react-window or similar |
| Missing indexes | Slow queries | Add database indexes |
| Unnecessary re-renders | Laggy UI | Use 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查询 | 数据库查询缓慢 | 使用 |
| 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: standardBuild 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:
- Why did the app crash? - User data was undefined
- Why was user data undefined? - API returned null
- Why did API return null? - Database query returned no rows
- Why were there no rows? - User ID was incorrect
- Why was user ID incorrect? - Route parameter parsing failed
Root cause: Route parameter parsing doesn't handle edge cases.
深入挖掘根本原因。
示例:
- 应用为什么崩溃? - 用户数据为undefined
- 用户数据为什么是undefined? - API返回null
- API为什么返回null? - 数据库查询未返回行
- 为什么没有查询到行? - 用户ID不正确
- 用户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: minimalCommon 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: standardGit 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.0Test, then mark:
测试,然后标记:
git bisect good # or bad
git bisect good # 或 bad
Repeat until culprit commit found
重复直到找到问题提交
undefinedundefinedPhase 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 for detailed patterns organized by category.
references/debugging-patterns.md查看获取按类别组织的详细模式。
references/debugging-patterns.mdError Pattern Detection
错误模式检测
Use to find multiple error patterns at once.
discoveryaml
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使用同时查找多种错误模式。
discoveryaml
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: locationsSystematic 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: locationsPrecision 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: standardPrecision 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: standardPrecision 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: minimalValidation Script
验证脚本
Use to validate debugging practices.
scripts/validate-debugging.shbash
./scripts/validate-debugging.sh /path/to/projectThe 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.shbash
./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:
- Comment out half the function
- If error persists, problem is in remaining half
- If error disappears, problem is in commented half
- Repeat until isolated
对于复杂问题,使用二分查找缩小范围。
注释掉一半代码:
- 注释掉函数的一半
- 如果错误仍然存在,问题在剩余部分
- 如果错误消失,问题在注释部分
- 重复直到定位问题
Rubber Duck Debugging
橡皮鸭调试
Explain the problem out loud:
- Describe what the code should do
- Describe what it actually does
- Walk through line by line
- Often reveals the issue during explanation
大声解释问题:
- 描述代码应该做什么
- 描述代码实际做什么
- 逐行走查
- 通常在解释过程中就能发现问题
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.0Test each commit
测试每个提交
git bisect good # or bad
undefinedgit bisect good # 或 bad
undefinedLogging 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
资源
- - Common error patterns by category
references/debugging-patterns.md - - Automated debugging practice validation
scripts/validate-debugging.sh - Chrome DevTools - https://developer.chrome.com/docs/devtools/
- React DevTools - https://react.dev/learn/react-developer-tools
- Node.js Debugging Guide - https://nodejs.org/en/docs/guides/debugging-getting-started/
- - 按类别组织的常见错误模式
references/debugging-patterns.md - - 自动化调试实践验证
scripts/validate-debugging.sh - Chrome DevTools - https://developer.chrome.com/docs/devtools/
- React DevTools - https://react.dev/learn/react-developer-tools
- Node.js调试指南 - https://nodejs.org/en/docs/guides/debugging-getting-started/