调试是开发中最耗时的环节之一。Claude Code 在这方面特别擅长——不只是看报错信息,它能追踪代码执行路径、分析多文件依赖、推断根本原因。本文整理调试中最实用的技巧和 Prompt 模板。
基础原则:给 Claude 完整的错误上下文
差的做法:
我的代码报错了,帮我修
好的做法:
运行 npm run build 时报这个错误:
[完整错误信息和堆栈追踪]
这个问题在昨天加了 [功能描述] 之后开始出现。
相关文件:src/auth/middleware.ts, src/routes/user.ts
技巧 1:直接贴完整错误信息
bash
# 把错误输出直接传给 Claude
npm run build 2>&1 | claude -p "Analyze this build error and fix it"
# 或在交互模式里
# 复制完整错误(包括堆栈),粘贴给 Claude必须包含:错误类型、错误消息、完整堆栈追踪(不要只截图一部分)。
技巧 2:让 Claude 系统分析根因
This error occurs randomly under high load:
Error: Cannot read property 'userId' of undefined
at AuthMiddleware.verify (src/auth/middleware.ts:42)
[完整堆栈]
Analyze the root cause systematically:
1. Trace the execution path that leads to this error
2. Identify under what conditions userId could be undefined
3. Check if it's a race condition, async issue, or data validation problem
4. Propose a fix with error handling
技巧 3:让 Claude 添加调试日志
Add strategic debug logging to help trace the bug.
For each key function in src/payment/processor.ts:
- Log inputs at function entry
- Log the state before each async call
- Log any error with full context
Use structured logging: console.log(JSON.stringify({fn, step, data}))
技巧 4:复现步骤+最小化复现
Bug report: User payment fails on the second attempt.
Steps to reproduce:
1. Add item to cart
2. Attempt checkout -> payment succeeds
3. Go back and attempt checkout again -> payment fails with Error: duplicate_transaction
Analyze the payment flow code in src/payment/ and find why the second attempt fails.
Focus on: session state, idempotency key handling, request deduplication.
技巧 5:多文件依赖追踪
The function processOrder() in src/orders/service.ts throws:
"Invalid user state: account locked"
But I can't find where this error originates.
Please:
1. Search all files for where "account locked" is thrown/set
2. Trace the call chain back to processOrder()
3. Show me the full dependency graph for this error path
技巧 6:性能问题定位
The /api/dashboard endpoint takes 8 seconds to respond.
Expected: <200ms. Here's the route handler: [code]
Analyze for performance issues:
1. Identify N+1 query patterns
2. Find unnecessary sequential awaits that could be parallel
3. Check for missing database indexes based on query patterns
4. Estimate the impact of each fix
技巧 7:TypeScript 类型错误
TypeScript error:
Type 'User | null' is not assignable to type 'User'
at src/dashboard/UserProfile.tsx:23
Fix all TypeScript type errors in this file.
Don't use 'any' as a workaround - fix the actual types.
Show me what type guards or assertions are needed.
技巧 8:让 Claude 写回归测试防止复现
Bug 修复后,立刻让 Claude 写测试:
You just fixed the duplicate payment bug.
Now write a test that:
1. Reproduces the exact bug scenario (second payment attempt)
2. Verifies the fix works
3. Tests edge cases: what if the first payment is still pending?
Add it to tests/payment.test.ts
各语言调试最佳实践
Python
Run: python -m pytest tests/test_auth.py -v --tb=long 2>&1
Share the full output. I need to see which tests fail and the exact assertion errors.
JavaScript / Node.js
Enable verbose error output:
NODE_OPTIONS='--stack-trace-limit=50' node app.js 2>&1
For async errors, add: process.on('unhandledRejection', (r, p) => console.error(r))
Docker / 容器环境
Show me the container logs:
docker logs my-app --tail=100 --since=10m 2>&1
Also check the container environment:
docker exec my-app env | grep -E 'DB|API|SECRET'
(mask the actual values)
调试会话流程
# 推荐的完整调试流程
1. 描述 Bug:症状、频率、触发条件
"This happens only in production, 0.1% of requests, always when user has >1000 orders"
2. 提供错误信息:完整堆栈
3. 提供上下文:最近改动了什么
"Started after deploy on March 14, changed payment retry logic"
4. 让 Claude 分析:不要直接让它修,先让它告诉你根因
"What do you think is causing this? Give me 3 possible causes ranked by likelihood"
5. 确认分析后再修复
"Yes, the race condition theory makes sense. Now fix it."
6. 验证并写测试
来源:Anthropic 官方文档 + Claude Code 实战