跳至主要內容
Debugging Techniques Workflow Agents

使用 Claude Code 除錯:進階技巧

超越基本的錯誤訊息。學習如何運用 debugger agent、test-runner 以及平行調查來進行系統性的根因分析。

2026年1月10日 15 分鐘閱讀 作者:ClaudeWorld

除錯是 Claude Code 真正展現實力的領域。你可以運用 Claude 理解上下文、分析模式和推理行為的能力,搭配專為除錯設計的專業 agents,而非手動追蹤程式碼。

本指南涵蓋官方除錯 agents、用於平行調查的 Task 工具,以及超越「修復這個錯誤」的進階技巧。

官方除錯工具

debugger Agent

根據 Claude Code 文件debugger agent 是專門用於系統性根因分析的專業子代理:

Task({
  subagent_type: "debugger",
  model: "sonnet",
  prompt: `
    Investigate: TypeError: Cannot read property 'id' of undefined
    at CheckoutForm.handleSubmit (checkout.tsx:45)

    Context: Error occurs when submitting checkout with empty cart.
    Find root cause and suggest fix.
  `
})

何時使用 debugger agent:

  • 需要深度分析的錯誤調查
  • 複雜 bug 的根因分析
  • 需要追蹤多個檔案的系統性追蹤
  • 理解非預期行為

test-runner Agent

test-runner agent 驗證修復並確保沒有 regression:

Task({
  subagent_type: "test-runner",
  model: "haiku",
  prompt: `
    Run tests related to checkout functionality.
    Analyze any failures and report coverage gaps.
  `
})

何時使用 test-runner agent:

  • 實作修復之後
  • 驗證重現測試通過
  • 檢查 regression 覆蓋率
  • 分析測試覆蓋率缺口

用於 Bug 搜尋的 Explore Agent

Explore agent(由 Haiku 4.5 驅動)擅長快速的程式碼庫調查:

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: `
    Explore authentication module (thoroughness: medium).
    Find all places where user session might be null.
  `
})

徹底程度等級:

等級時間使用情境
quick10-30s尋找特定錯誤模式
medium30-60s對應相關程式碼路徑
very thorough60-120s完整流程分析

除錯思維轉變

傳統除錯方式

1. 看到錯誤
2. Google 錯誤訊息
3. 嘗試隨機的 Stack Overflow 解法
4. 加入 console.log 語句
5. 重複直到修復

Claude Code 除錯方式

1. 看到錯誤
2. 啟動平行調查 agents
3. 讓 agents 追蹤根因
4. 理解為什麼發生
5. 用 test-runner 驗證正確修復

差異在於:Claude 不只是修復症狀——它理解疾病本身。

技巧 1:提供豐富上下文的錯誤報告

不要只是貼上錯誤。給 Claude 完整的故事。

不好的方式

"Fix this error: TypeError: Cannot read property 'id' of undefined"

好的方式

"I'm getting this error when submitting the checkout form:

Error: TypeError: Cannot read property 'id' of undefined
  at CheckoutForm.handleSubmit (checkout.tsx:45)
  at processOrder (orders.ts:123)
  at <anonymous>

What I was doing:
- Logged in as test user
- Added 2 items to cart
- Clicked submit on checkout

What I expected:
- Order to be created
- Redirect to confirmation page

The error started after I merged PR #234 yesterday.
Relevant recent changes: Updated cart state management."

為什麼這樣有效

Claude 現在可以:

  • 追蹤 stack 找到源頭
  • 將最近的變更視為嫌疑犯
  • 理解預期行為
  • 在腦中重現情境

技巧 2:使用 Task 工具進行平行調查

根據官方 Claude Code 文件,對複雜 bug 使用多代理分析:

// Launch 5 parallel investigation agents
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Search for session/cookie handling changes this week (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Analyze authentication middleware patterns (thoroughness: medium)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Check for race conditions in auth state (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Review error logs for auth-related errors (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Find timeout/expiry configuration changes (thoroughness: quick)"
})

時間比較:

  • 循序調查:5 × 30s = 150 秒
  • 平行調查:max(30s) = 30 秒
  • 快 5 倍

每個 agent 專注於一個假設。第一個找到強力證據的會引導調查方向。

技巧 3:Debugger-Test Runner 工作流程

結合 debugger 和 test-runner agents 進行全面除錯:

第一階段 - 調查(debugger agent):
→ 分析錯誤和 stack trace
→ 識別根因
→ 提出修復方案

第二階段 - 驗證(test-runner agent):
→ 執行現有測試
→ 驗證修復不會破壞其他功能
→ 建議額外的測試覆蓋

第三階段 - 預防 Regression:
→ 建立重現測試
→ 確保測試在沒有修復時失敗
→ 確保測試在修復後通過

實作:

// Phase 1: debugger investigates
Task({
  subagent_type: "debugger",
  model: "sonnet",
  prompt: `
    Investigate checkout failure.
    Error: TypeError at checkout.tsx:45
    Find root cause and propose fix.
  `
})

// Phase 2: test-runner verifies (after fix)
Task({
  subagent_type: "test-runner",
  model: "haiku",
  prompt: `
    Run all checkout-related tests.
    Report any failures and coverage analysis.
  `
})

技巧 4:行為分析

當你知道有問題但無法精確定位時。

"Something's wrong with the search feature. Results seem off.

Behavior I'm seeing:
- Search for 'javascript' returns Python articles
- Exact title matches don't appear first
- Results change on page refresh (shouldn't happen)

Help me understand:
1. What search algorithm are we using?
2. Where is the ranking logic?
3. What could cause non-deterministic results?
4. How can we add debugging to trace a query?"

Claude 會:

  • 對應搜尋流程
  • 識別每個階段的潛在問題
  • 建議插入點
  • 協助建立除錯計畫

技巧 5:使用 Git 整合進行 Regression 追蹤

當某個原本運作的功能突然壞掉時:

"The export feature broke. It was working on Friday.

git log shows these changes since Friday:
- abc123: Updated PDF library
- def456: Refactored file service
- ghi789: Added new export format

Help me:
1. Identify which commit most likely caused the regression
2. Explain what each change does
3. Suggest how to verify the culprit
4. Provide a fix if you can identify the issue"

平行分析方式:

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Analyze commit abc123 impact on export feature (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Analyze commit def456 impact on export feature (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Analyze commit ghi789 impact on export feature (thoroughness: quick)"
})

技巧 6:錯誤模式分析

對於重複或相關的錯誤:

"We're seeing multiple related errors in production:

1. TypeError: Cannot read 'user' of null (dashboard.tsx)
2. TypeError: Cannot read 'profile' of null (settings.tsx)
3. TypeError: Cannot read 'preferences' of null (notifications.tsx)

All involve user data. What's the common cause?
Why might user be null in these places?"

Claude 會:

  • 識別共同模式(使用者資料存取)
  • 追蹤使用者資料流
  • 找到 null 的起源
  • 建議系統性修復

技巧 7:效能除錯

當事情變慢時,使用平行效能分析:

// Launch parallel performance investigation
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Find N+1 query patterns in dashboard data fetching (thoroughness: medium)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Identify waterfall request patterns in API calls (thoroughness: medium)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Find unnecessary re-renders in React components (thoroughness: quick)"
})

Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Check for missing database indexes on slow queries (thoroughness: quick)"
})

技巧 8:狀態除錯

對於複雜的狀態管理問題:

"The shopping cart state is getting corrupted.

Symptoms:
- Items appear/disappear randomly
- Quantities reset to 1
- Total doesn't match items

We use Redux Toolkit. Cart slice is in store/cart.ts.

I suspect a race condition but can't reproduce it consistently.
Help me trace where state mutations might be happening incorrectly."

Claude 會:

  • 分析 cart reducer
  • 找到潛在的 mutation 問題
  • 識別非同步 actions 中的 race conditions
  • 建議狀態除錯工具

使用官方工具的除錯工作流程

步驟 1:收集上下文並啟動調查

// Launch parallel investigation
Task({
  subagent_type: "Explore",
  model: "haiku",
  prompt: `
    Explore error context (thoroughness: medium).
    Find all files related to: [error location]
    Map data flow and dependencies.
  `
})

步驟 2:使用 debugger Agent 進行深度分析

Task({
  subagent_type: "debugger",
  model: "sonnet",
  prompt: `
    Context from exploration: [results]
    Error: [full stack trace]

    Perform root cause analysis:
    1. Trace execution path
    2. Identify failure point
    3. Determine fix
  `
})

步驟 3:使用 test-runner Agent 驗證

Task({
  subagent_type: "test-runner",
  model: "haiku",
  prompt: `
    After fix applied to [files]:
    1. Run related tests
    2. Check for regressions
    3. Report coverage
  `
})

步驟 4:預防 Regression

識別原因後:
- 理解「為什麼」發生
- 修復根因,而非只是症狀
- 加入測試以預防 regression
- 檢查其他地方是否有類似問題

常見除錯模式

Null Reference 模式

Error: Cannot read property 'X' of undefined

要問的問題:
- X 應該從哪裡來?
- 什麼條件會讓它變成 undefined?
- 是否有 race condition?
- 是否缺少初始化?

非同步時序模式

症狀:間歇性失敗,有時可以運作

要問的問題:
- 是否有 race conditions?
- Promises 是否正確處理?
- 是否缺少 await?
- 是否有時序假設?

狀態 Mutation 模式

症狀:UI 不更新,資料過時

要問的問題:
- 狀態是否被直接修改?
- 是否遵循不可變性規則?
- useEffect 中的 dependencies 是否正確?
- Memoization 是否正確運作?

整合模式

症狀:本地可以運作,正式環境失敗

要問的問題:
- 環境變數是否正確?
- URLs/endpoints 是否正確?
- 是否有網路/CORS 問題?
- 是否有 timeout 差異?

除錯的模型選擇

根據 Claude Code CHANGELOG

任務建議模型原因
快速檔案搜尋Haiku 4.5快速、便宜
模式比對Haiku 4.5快速、便宜
根因分析Sonnet 4.5平衡的推理能力
複雜除錯Sonnet 4.5支援 Extended Thinking
關鍵 bug 修復Opus 4.5最高智慧

快速切換模型(v2.0.65+):在提示輸入時按 Option+P(macOS)或 Alt+P(Windows/Linux)。

實際案例:Bug 調查

使用者:"Production error: 'Payment failed' but money was charged."

平行調查(5 個 Explore agents):
→ 搜尋 payment logs 中的錯誤模式
→ 分析 payment service 的錯誤處理
→ 檢查 Stripe webhook handlers
→ 審查最近的 payment 變更
→ 在錯誤追蹤中尋找類似問題

結果:
- Agent 3 發現:Webhook handler 在 timeout 時不會重試
- Agent 4 確認:最近的變更新增了 timeout 邏輯
- Agent 1 顯示:模式在 1 月 5 日部署後開始出現

~1 分鐘識別根因,相比循序執行需要 10 分鐘以上。

開始行動

今天:

  1. 在下一個 bug 上嘗試 debugger agent
  2. 使用平行 Explore agents 進行調查
  3. 用 test-runner agent 驗證修復

這週:

  1. 開發除錯提示模板
  2. 對複雜 bug 使用平行調查
  3. 為每個修復建立重現測試

這個月:

  1. 為常見問題建立除錯模式
  2. 整合 debugger + test-runner 工作流程
  3. 與團隊分享模式

目標不只是更快地修復 bug——而是透過每次除錯過程更好地理解你的程式碼庫。


資料來源:Claude Code DocumentationClaude Code GitHubCHANGELOG