跳至主要內容

使用 Claude Code 除錯:進階技巧

Claude Code 進階除錯技巧:用自訂的 debugger 與 test-runner subagent、Explore agent 平行調查,搭配富含上下文的錯誤報告、Git regression 追蹤與常見錯誤模式,系統性找出根本原因。

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

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

2026 年 10 月 21 日更新: 範例改用 Agent 工具與目前的模型;說明 debugger 與 test-runner 是你自訂的 subagent(內建的是 Explore、Plan 與 general-purpose);更正 Explore 的模型與任務清單工具的可用性;並補上 /debug 指令。

官方除錯工具

debugger Agent

Claude Code 內建的 subagent 是 Explore、Plan 與 general-purpose;debugger 則是你在 .claude/agents/debugger.md 中自訂、用於系統性根因分析的 subagent。若想直接使用內建功能,可執行 /debug:這個內建 skill 會為此 session 開啟除錯日誌,並從日誌開始調查。

---
name: debugger
description: Investigates errors and test failures to find the root cause. Use for stack traces and unexpected behavior.
tools: Read, Glob, Grep, Bash
model: sonnet
---

You are a debugger. Reproduce the problem, trace it to its root cause,
and propose the smallest fix that addresses the cause rather than the symptom.

之後 Claude 會透過 Agent 工具(v2.1.63 之前叫 Task,Task(...) 仍可作為別名使用)委派給它:

Agent({
  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 同樣是自訂的 subagent,用來驗證修復並確保沒有 regression:

Agent({
  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,擅長快速的程式碼庫調查:它被禁止使用 Write 與 Edit。預設情況下它使用主對話的模型(主對話若是 Fable,則使用 opus 別名對應的模型)。呼叫時傳入的 model 優先序最高,所以下面的範例都把探索留在 Haiku 上;若在 .claude/agents/ 中自訂一個 Explore agent,則會覆寫內建版本。

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

徹底程度等級: Claude 會依需求傳入 quick(針對性查詢)、medium(平衡探索)或 very thorough(完整分析)。

等級使用情境
quick尋找特定錯誤模式
medium對應相關程式碼路徑
very thorough完整流程分析

除錯思維轉變

傳統除錯方式

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:使用 Agent 工具進行平行調查

根據官方 subagents 文件,對複雜 bug 使用多代理分析。把這些呼叫放在同一則訊息中送出,它們就會並行執行:

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

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

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

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

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

時間比較:

  • 循序調查:5 × 30s = 150 秒
  • 平行調查:max(30s) = 30 秒
  • 最佳情境示例: 未計入啟動與協調開銷時,牆鐘時間約為循序執行的五分之一

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

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

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

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

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

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

實作:

// Phase 1: debugger investigates
Agent({
  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)
Agent({
  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"

平行分析方式:

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

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

Agent({
  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
Agent({
  subagent_type: "Explore",
  model: "haiku",
  prompt: "Find N+1 query patterns in dashboard data fetching (thoroughness: medium)"
})

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

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

Agent({
  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
  • 建議狀態除錯工具

使用 Subagent 的除錯工作流程

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

// Launch parallel investigation
Agent({
  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 進行深度分析

Agent({
  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 驗證

Agent({
  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 模型設定文件:

任務建議模型原因
快速檔案搜尋Haiku 5.5快速、便宜
模式比對Haiku 5.5快速、便宜
根因分析Sonnet 5.5平衡的推理能力
複雜除錯Opus 5.5預設模型;可用 /effort high 提高推理力度
關鍵 bug 修復Fable 5.1最高智慧,最適合長時間的調查

Opus 5.5、Sonnet 5.5 與 Haiku 5.5 預設以 medium effort 執行,所以遇到難纏的 bug,通常該調整的是 /effort high 或 xhigh,而不是換模型。max 是最深的等級,且只套用於目前的 session。

快速切換模型(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. 在下一個 bug 上執行 /debug,後續再寫一個 debugger subagent 接手
  2. 使用平行 Explore agents 進行調查
  3. 用 test-runner agent 驗證修復

這週:

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

這個月:

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

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


資料來源:Claude Code Documentation、Subagents、指令、模型設定、Claude Code GitHub