使用問題
用Claude Code時,你可能會遇到各種問題——命令不生效、輸出不符合預期、檔案操作失敗、Agent卡住、效能慢等。這些問題讓人頭大,但大部分都有明確的解決辦法。
本文系統介紹常見問題、排查思路和解決方案,幫你快速解決問題,讓AI程式設計助手真正成為效率倍增器。
命令不生效
問題1: Claude執行了命令但沒有任何效果
現象描述:
你: 运行测试
Claude: 好的,我来运行测试。
[执行命令 npm test]
[命令输出显示测试通过]
你: 为什么测试没有实际运行?我刚才改了代码应该会失败的
可能原因和解決方案:
原因1: 工作目錄不正確
Claude Code可能在錯誤的目錄執行了命令。
# 检查当前工作目录
pwd
# 如果不是项目根目录,明确指定路径
你: 在 /Users/username/my-project 目录下运行测试
解決方案:
在CLAUDE.md中明確指定專案路徑:
## Project Location
Always use absolute paths. The project is located at:
- Project root: `/Users/username/projects/my-project`
- Source code: `/Users/username/projects/my-project/src`
- Tests: `/Users/username/projects/my-project/tests`
或者在對話中明確指定路徑:
你: 在项目根目录/Users/username/my-project下运行npm test
原因2: 命令執行環境變數缺失
某些命令需要特定的環境變數才能正常工作。
解決方案:
# 方案1: 在命令前设置环境变量
你: 运行 API_KEY=xxx npm test
# 方案2: 在CLAUDE.md中声明必需的环境变量
你: 需要先加载.env文件,然后运行测试
# 方案3: 明确告诉Claude使用哪个环境
你: 使用开发环境配置运行测试
在CLAUDE.md中新增:
## Environment Setup
Required environment variables:
- `NODE_ENV`: development|production|test
- `DATABASE_URL`: PostgreSQL connection string
- `API_KEY`: API authentication key
Before running commands, ensure:
1. .env file is loaded
2. Environment is set to development for local work
原因3: 命令執行順序錯誤
你: 安装依赖并运行项目
Claude: [只运行了 npm start,没有安装依赖]
解決方案:
使用&&連線命令,確保順序執行:
你: 先安装依赖,然后运行项目
Claude: 好的,我会运行 npm install && npm start
# 或者在CLAUDE.md中明确工作流
你: 按照"安装依赖 -> 配置环境 -> 运行项目"的顺序执行
問題2: 斜槓命令(/)不工作
現象描述:
/commit
claude: /commit: command not found
可能原因和解決方案:
原因1: 不在Claude Code會話中
斜槓命令只在Claude Code CLI中可用,不能在系統shell中直接使用。
解決方案:
# 错误 - 在系统shell中
$ /commit # 不工作
# 正确 - 在Claude Code会话中
$ claude
claude> /commit # 正常工作
原因2: 命令拼寫錯誤
/commmit # 错误: 多了一个m
/commmit # 应该是 /commit
解決方案:
# 使用/help查看所有可用命令
/help
# 常用命令列表:
/commit # 创建git提交
/edit # 编辑文件
/read # 读取文件
/search # 搜索代码
/test # 运行测试
/init # 初始化CLAUDE.md
原因3: 命令在當前上下文中不可用
某些命令需要特定的上下文(如git倉庫)。
解決方案:
# /commit需要git仓库
git init # 如果还没初始化
# /edit需要指定文件
/edit file.js # 明确指定要编辑的文件
問題3: Claude誤解了命令意圖
現象描述:
你: 更新按钮样式
Claude: [修改了Button组件的所有样式,而不是只更新你想要改的那一部分]
解決方案:
方案1: 更具體地描述需求
# 不够具体
你: 更新按钮样式
# 更好的方式
你: 更新主按钮(primary button)的背景色为蓝色,保持其他按钮不变
方案2: 明確檔案和位置
你: 在 src/components/Button/Button.js 文件中,
将 .primary 类的 background-color 从 red 改为 blue
方案3: 提供前後對比
你: 把这段代码:
.button { background: red; }
改成:
.button { background: blue; }
方案4: 在CLAUDE.md中定義術語
## Terminology
When I say "button", I mean:
- Primary button: `.btn-primary` class
- Secondary button: `.btn-secondary` class
- Link button: `.btn-link` class
"Update button styles" means update ALL button types.
"Update primary button" means ONLY `.btn-primary`.
輸出不符預期
問題4: Claude生成的程式碼不符合專案規範
現象描述:
你: 创建一个用户服务
Claude: [创建了 class UserService { ... }]
你: 不对,我们项目使用函数式编程风格,不用class
解決方案:
方案1: 更新CLAUDE.md配置
## Coding Conventions
### Style Requirements
- **MUST** use functional programming style
- **MUST NOT** use classes (except for React components)
- **PREFER** pure functions
- **PREFER** composition over inheritance
### Example
```typescript
// ❌ BAD - Don't use classes
class UserService {
getUser(id) { ... }
}
// ✅ GOOD - Use functions
export const userService = {
getUser: (id: string) => { ... }
};
#### 方案2: 提供程式碼示例
```bash
你: 创建一个用户服务,类似现有的订单服务
Claude: [会参考现有代码风格]
# 或者直接给出示例
你: 创建一个用户服务,像这样:
export const userService = {
getById: (id) => {...},
create: (data) => {...}
};
方案3: 在對話中糾正
你: 不对,我们项目不使用class。请用函数式风格重写
Claude: 明白了,我来用函数式风格重写
問題5: Claude過度修改程式碼
現象描述:
你: 修复这个函数的类型错误
Claude: [不仅修复了类型,还重构了整个文件,添加了很多不需要的代码]
解決方案:
方案1: 明確修改範圍
你: 只修改 getUserById 函数的类型错误,
不要改动其他代码
# 或者更具体
你: 在第15-20行的 getUserById 函数中,
将 userId 参数类型从 string 改为 number
方案2: 使用最小修改原則
## Editing Guidelines
### Conservative Editing
- **MUST** make minimal changes to fix the issue
- **MUST NOT** refactor unless explicitly asked
- **MUST NOT** add new features
- **SHOULD** preserve existing code style
- **MUST** ask before making large changes
### When I say "fix X":
- Fix X only
- Don't improve other things
- Don't refactor related code
方案3: 使用Edit工具的精確匹配
你: 只替换这一段:
old:
function getUser(userId: string) { ... }
new:
function getUser(userId: number) { ... }
問題6: Claude忽略了重要的約束條件
現象描述:
你: 创建一个登录页面,不要使用任何UI库
Claude: [使用了 Material-UI]
你: 我说不要用UI库!
解決方案:
方案1: 在CLAUDE.md中明確定義約束
## Project Constraints
### What to Use
- Vanilla CSS only (no Tailwind, no CSS-in-JS)
- React hooks (no class components)
- Fetch API (no axios)
### What NOT to Use
❌ DO NOT use UI libraries (Material-UI, Ant Design, etc.)
❌ DO NOT use state management libraries (Redux, MobX, etc.)
❌ DO NOT use form libraries (Formik, React Hook Form, etc.)
方案2: 使用強調性語言
你: 创建一个登录页面,**重要**:只使用原生CSS,
不要使用任何UI组件库,不要使用Tailwind,
不要使用styled-components
# 或者使用列表形式
你: 创建登录页面,要求:
1. 使用原生CSS
2. 不使用UI库
3. 不使用CSS-in-JS
方案3: 分步驟驗證
你: 第一步创建登录页面的HTML结构,
然后等我确认后再添加样式
Claude: [创建HTML]
你: 确认。第二步添加原生CSS样式,
不要使用任何CSS框架
Claude: [添加原生CSS]
檔案操作失敗
問題7: 找不到檔案或目錄
現象描述:
你: 读取 config/settings.json
Claude: Error: File not found: config/settings.json
可能原因和解決方案:
原因1: 相對路徑錯誤
Claude Code的工作目錄可能不是你期望的。
解決方案:
# 检查当前目录
pwd
# 使用绝对路径
你: 读取 /Users/username/project/config/settings.json
# 或者在CLAUDE.md中定义项目路径
你: 项目根目录是/Users/username/project
原因2: 檔名拼寫錯誤
# 常见错误
你: 读取 config/setting.json # 少了一个s
# 实际文件名是 settings.json
解決方案:
# 先搜索文件
你: 搜索包含"setting"的配置文件
# 或使用通配符
你: 列出 config 目录下的所有json文件
原因3: 檔案尚未建立
你: 读取新创建的用户模型
Claude: File not found
解決方案:
# 检查文件是否存在
ls -la src/models/User.js
# 如果不存在,先创建
你: 先检查文件是否存在,如果不存在就创建它
在CLAUDE.md中新增:
## File Operations
### Before Reading Files
1. Check if file exists using `ls` command
2. If file doesn't exist, ask user whether to create it
3. Use absolute paths when in doubt
### Common File Locations
- Models: `src/models/`
- Controllers: `src/controllers/`
- Configs: `config/`
- Tests: `tests/`
問題8: 檔案寫入許可權問題
現象描述:
Claude: Error: Permission denied when writing to file
解決方案:
方案1: 檢查檔案許可權
# 检查文件权限
ls -la file.js
# 修改权限
chmod +w file.js
方案2: 使用sudo(謹慎使用)
你: 使用sudo权限写入文件
Claude: sudo echo "content" > file.js
方案3: 檢查檔案是否被鎖定
# 检查是否有进程占用文件
lsof | grep file.js
# 关闭占用文件的编辑器或IDE
問題9: 編輯檔案時格式被破壞
現象描述:
你: 在函数开头添加一行注释
Claude: [添加了注释,但整个文件的缩进都乱了]
解決方案:
方案1: 使用格式化工具
你: 修改文件后,运行prettier格式化
Claude: [修改代码] -> [运行 npx prettier --write file.js]
在CLAUDE.md中配置:
## Code Formatting
### After Editing
After making changes to files, ALWAYS run:
```bash
npx prettier --write [modified-files]
npm run lint -- --fix
Formatter Config
- Tool: Prettier
- Line width: 100
- Indent: 2 spaces
- Quotes: single
#### 方案2: 使用Edit工具的精確匹配
```bash
你: 只替换这一行:
old:
export function getData() {
new:
// Fetch data from API
export function getData() {
注意:不要改动其他行的缩进
方案3: 分步小修改
你: 第一步:只在函数开头添加注释,不要做其他改动
Claude: [添加注释]
你: 第二步:格式化文件
Claude: [运行格式化工具]
問題10: 檔案操作後內容丟失
現象描述:
你: 更新用户列表组件
Claude: [更新了组件]
你: 等等,我之前的修改怎么不见了?
可能原因和解決方案:
原因1: Claude覆蓋了整個檔案
解決方案:
# 要求只修改特定部分
你: 只修改 renderUserList 函数,
不要改动其他代码
# 或者明确说明
你: 在保留其他代码的前提下,
更新 renderUserList 函数的实现
在CLAUDE.md中配置:
## File Editing Rules
### Partial Edits
- **PREFER** Edit tool over Write tool
- **MUST** preserve existing code unless told to replace
- **MUST** use smallest possible change
- **MUST NOT** reformat entire file unless requested
### When to Use Write Tool
Only when user says:
- "Replace the entire file"
- "Rewrite this component"
- "Create a new file"
### Default Behavior
Use Edit tool with specific old_string/new_string pairs.
原因2: Git衝突沒有解決
解決方案:
# 检查git状态
git status
# 如果有冲突,先解决
你: 检查git状态,如果有冲突先解决冲突,
然后再修改文件
Agent卡住
問題11: Claude長時間沒有響應
現象描述:
你: 重构整个项目的组件结构
Claude: [思考中...] [30分钟过去了还在思考]
可能原因和解決方案:
原因1: 任務過於複雜
解決方案:
# 中断当前任务
Ctrl+C
# 分解任务
你: 第一步:先分析现有组件结构
Claude: [快速完成分析]
你: 第二步:提出重构方案
Claude: [提供方案]
你: 第三步:先重构一个组件作为示例
Claude: [重构示例]
原因2: 陷入分析迴圈
Claude可能在反覆分析和重新分析。
解決方案:
# 使用think模式
你: 使用think模式,快速给出方案,
不要过度分析
# 或者直接给出指令
你: 给出一个可行的方案就可以,
不需要分析所有可能性
原因3: 等待外部資源
Claude可能在等待網路請求、檔案讀取等操作。
解決方案:
# 检查是否在执行耗时操作
ps aux | grep claude
# 如果确实在执行,耐心等待
# 如果怀疑卡住,中断并重试
Ctrl+C
你: 重试刚才的操作
在CLAUDE.md中配置:
## Performance Guidelines
### Task Complexity
For large tasks (>10 files), break them down:
1. Analysis phase: List what needs to be done
2. Planning phase: Create step-by-step plan
3. Execution phase: Execute one step at a time
4. Verification phase: Test each step
### Timeouts
- Single file edit: < 30 seconds
- Multi-file changes: < 2 minutes
- Large refactoring: < 5 minutes
- If taking longer, break into smaller tasks
問題12: Claude陷入迴圈
現象描述:
Claude: 我来修复这个问题
[修改代码]
Claude: 还有错误,继续修复
[再次修改]
Claude: 还有错误...
[无限循环]
解決方案:
方案1: 中斷並重新思考
Ctrl+C
你: 停止。先分析为什么一直失败,
找出根本原因
方案2: 限制嘗試次數
你: 尝试修复这个问题,最多尝试3次。
如果3次后还有问题,停下来告诉我原因
在CLAUDE.md中配置:
## Error Handling
### Retry Policy
- Maximum 3 attempts for fixes
- After 3 failures, stop and ask for help
- Provide error messages and context
- Suggest alternative approaches
### When Stuck
If you encounter repeated errors:
1. Stop after 3 attempts
2. Analyze the error pattern
3. Report findings to user
4. Suggest alternative solutions
方案3: 請求人工介入
你: 如果这个问题自动修复失败,
停下来给我提供详细信息,
我会手动修复
問題13: Claude忘記了上下文
現象描述:
你: 创建一个用户服务
Claude: [创建了 UserService]
你: 现在创建一个产品服务,和用户服务类似
Claude: [创建了完全不同风格的 ProductService]
你: 我说和用户服务类似!
Claude: 抱歉,我忘记了之前的上下文
解決方案:
方案1: 明確引用
你: 创建产品服务,参考刚才创建的
src/services/UserService.js 的结构
方案2: 使用Todo列表
你: 创建任务列表:
1. 创建用户服务
2. 基于用户服务的模式创建产品服务
3. 基于用户服务的模式创建订单服务
方案3: 在CLAUDE.md中定義模式
## Service Pattern
All services should follow this pattern:
```typescript
export const [Name]Service = {
// Repository methods
getAll: async () => { ... },
getById: async (id: string) => { ... },
create: async (data: CreateInput) => { ... },
update: async (id: string, data: UpdateInput) => { ... },
delete: async (id: string) => { ... },
// Business logic methods
[customMethod]: async (...) => { ... }
};
Examples: See src/services/UserService.ts
## 效能緩慢
### 問題14: 響應速度很慢
**現象描述:**
Claude的響應速度明顯變慢,每個操作都要等待很長時間。
**可能原因和解決方案:**
#### 原因1: 專案檔案過多
Claude需要掃描和分析大量檔案。
**解決方案:**
```bash
# 在CLAUDE.md中限制搜索范围
你: 只在src目录下搜索,
忽略node_modules、dist、build等目录
# 或者使用.gitignore
# 在项目根目录创建.gitignore
node_modules/
dist/
build/
.cache/
在CLAUDE.md中配置:
## Project Structure
### Directories to Ignore
When searching or analyzing:
- **IGNORE**: `node_modules/`, `dist/`, `build/`, `.cache/`
- **IGNORE**: `*.log`, `*.min.js`, `*.min.css`
- **FOCUS**: `src/`, `lib/`, `app/`
### Search Strategy
- Start with specific file paths when known
- Use glob patterns to narrow search scope
- Search in relevant directories only
原因2: 網路延遲
解決方案:
# 检查网络连接
ping claude.ai
# 如果网络不稳定,考虑:
# 1. 减少并发操作
你: 逐个处理这些文件,不要并发
# 2. 减少上下文大小
你: 只关注当前文件,
不需要分析整个项目
# 3. 使用缓存
你: 使用本地的代码缓存,
不要重复获取
原因3: 上下文過大
解決方案:
# 清理对话历史
你: 忘记之前的对话,
我们重新开始这个任务
# 或者明确限定范围
你: 只关注当前文件的功能,
不需要考虑整个系统
問題15: 記憶體佔用過高
現象描述:
Claude Code程序佔用大量記憶體,導致系統變慢。
解決方案:
# 检查内存使用
ps aux | grep claude
# 重启Claude Code
exit
claude
# 如果持续高内存,
考虑分批处理大任务
你: 先处理前10个文件,
完成后我们再继续
在CLAUDE.md中配置:
## Performance Optimization
### Large File Operations
For files > 1000 lines:
- Read in chunks using offset/limit
- Process one section at a time
- Use Read tool with limit parameter
### Batch Operations
When processing multiple files:
- Maximum 10 files per batch
- Wait for confirmation before next batch
- Provide progress updates
問題16: Token使用過快
現象描述:
API quota很快用完,或賬單費用過高。
解決方案:
方案1: 最佳化提示詞
# 冗长的提示词
你: 我希望你能够帮助我编写一个React组件,
这个组件需要包含以下功能:...[500字]
# 简洁的提示词
你: 创建一个带搜索功能的用户列表组件,
参考现有组件风格
方案2: 減少不必要的讀取
# 不好的做法
你: 读取package.json,读取tsconfig.json,
读取所有配置文件,然后创建组件
# 好的做法
你: 直接创建组件,
遇到配置问题再查看相关文件
方案3: 使用更精確的工具
# 使用Grep而不是Read多个文件
你: 搜索"interface User"定义
# 使用Glob而不是列出目录
你: 查找所有*.test.js文件
在CLAUDE.md中配置:
## Token Optimization
### Efficient File Reading
- **PREFER** Grep over Read when searching content
- **PREFER** Glob over Bash ls for finding files
- **READ** only the files you need, not entire directories
- **USE** offset/limit for large files
### Prompt Efficiency
- Keep prompts concise
- Use CLAUDE.md for persistent context
- Reference existing code instead of describing patterns
- Use technical terms over explanations
### Before Reading
Ask yourself:
1. Do I really need to read this file?
2. Can I search for specific content instead?
3. Can I use a more specific tool?
故障排查指南
系統化排查流程
當遇到問題時,按照以下步驟系統化地排查:
第一步:確認問題
# 1. 重现问题
你: 重复刚才的操作
# 2. 记录详细信息
- 问题现象
- 错误消息
- 操作步骤
- 预期结果 vs 实际结果
第二步:檢查環境
# 1. 检查Claude Code版本
claude --version
# 2. 检查认证状态
claude auth status
# 3. 检查项目配置
ls -la CLAUDE.md
cat CLAUDE.md
# 4. 检查git状态
git status
git log -1
第三步:隔離問題
# 1. 在新项目中测试
cd /tmp
mkdir test-project
cd test-project
claude
# 2. 使用最简单的任务测试
你: 创建一个hello.js文件,内容是console.log('hello')
# 3. 如果简单任务正常,
说明是项目特定问题
第四步:檢視日誌
# 1. Claude Code日志
# 通常在 ~/.claude/logs/
# 2. 启用详细模式
claude --verbose
# 3. 查看错误详情
你: 详细说明遇到的错误,
包括完整的错误堆栈
第五步:嘗試解決方案
# 1. 清除缓存
claude --clear-cache
# 2. 重新认证
claude auth logout
claude auth login
# 3. 重启Claude Code
exit
claude
常見錯誤診斷
錯誤1: Authentication errors
Error: Authentication failed
診斷步驟:
# 1. 检查认证状态
claude auth status
# 2. 重新登录
claude auth login
# 3. 检查API key
# 确保在Claude.ai上有有效的API配额
預防措施:
## Authentication Checklist
- [ ] Valid Claude.ai account
- [ ] API access enabled
- [ ] Sufficient API quota
- [ ] Network connectivity to claude.ai
- [ ] No VPN/firewall blocking
錯誤2: File system errors
Error: EACCES: permission denied
Error: ENOENT: no such file or directory
診斷步驟:
# 1. 检查文件权限
ls -la
# 2. 检查文件是否存在
test -f file.js && echo "exists" || echo "not found"
# 3. 检查磁盘空间
df -h
解決方案:
# 修复权限
chmod 644 file.js
chmod +x script.sh
# 创建目录
mkdir -p path/to/directory
# 清理磁盘
# 删除不必要的文件
錯誤3: Network errors
Error: Network timeout
Error: Connection refused
診斷步驟:
# 1. 测试网络连接
ping claude.ai
curl -I https://claude.ai
# 2. 检查DNS
nslookup claude.ai
# 3. 检查代理设置
echo $HTTP_PROXY
echo $HTTPS_PROXY
解決方案:
# 如果需要代理
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# 如果DNS有问题
# 尝试使用8.8.8.8
nslookup claude.ai 8.8.8.8
實用技巧和解決方案
技巧1: 使用模板化提示詞
在CLAUDE.md中定義常用任務模板:
## Task Templates
### Create New Component
When creating a component:
1. Check existing components in src/components/
2. Follow the same structure and style
3. Include TypeScript types
4. Add prop validation
5. Include JSDoc comments
6. Create test file alongside
### Debug Workflow
When debugging:
1. Reproduce the issue
2. Add console.log statements
3. Run in debug mode if needed
4. Identify root cause
5. Fix the issue
6. Add regression test
7. Remove debug code
### Refactoring Checklist
Before refactoring:
- [ ] Write tests for existing behavior
- [ ] Run tests to ensure they pass
- [ ] Make small, incremental changes
- [ ] Run tests after each change
- [ ] Update documentation
- [ ] Run full test suite
技巧2: 分階段處理複雜任務
# 不好的做法 - 一次性处理
你: 重构整个项目,把所有的callback改成async/await
# 好的做法 - 分阶段处理
你: 第一阶段:先分析哪些文件使用了callback
Claude: [列出文件]
你: 第二阶段:选一个简单的文件作为示例
Claude: [重构示例文件]
你: 第三阶段:验证重构后的代码是否正常工作
Claude: [运行测试]
你: 第四阶段:按照示例重构其他文件,
每次处理3-5个文件
Claude: [分批处理]
技巧3: 利用版本控制
# 在重大修改前创建分支
你: 创建一个新分支 refactor/async-await,
然后在分支上重构
# 定期提交
你: 每完成一个文件的修改就提交一次,
提交信息描述修改内容
# 出问题时回滚
你: 如果引入了问题,
使用git回滚到上一个正常工作的提交
在CLAUDE.md中配置:
## Git Workflow
### Before Making Changes
1. Create feature branch: `git checkout -b feature/name`
2. Ensure clean working directory: `git status`
3. Pull latest changes: `git pull`
### During Development
- Commit after each logical change
- Use descriptive commit messages
- Run tests before committing
- Push regularly for backup
### Commit Pattern
git add file.js git commit -m "fix: resolve async issue in getUser"
### If Something Goes Wrong
```bash
# Check what changed
git diff
# Undo uncommitted changes
git checkout -- file.js
# Revert commit
git revert HEAD
# Reset to previous commit
git reset --hard HEAD~1
### 技巧4: 建立驗證機制
```bash
# 每次修改后自动验证
你: 每次修改代码后,
自动运行相关测试并检查是否通过
# 或者使用watch模式
你: 启动测试的watch模式,
实时监控代码变化
在CLAUDE.md中配置:
## Validation Workflow
### After Code Changes
For every code change:
1. Run linter: `npm run lint`
2. Run formatter: `npm run format`
3. Run tests: `npm test`
4. Type check: `npm run type-check`
### Auto-Verification
Tell Claude to automatically validate:
"After making changes, run the full validation suite and report any issues."
### Continuous Testing
For watch mode:
"After starting development, run tests in watch mode using `npm run test:watch`"
技巧5: 使用漸進式提示
# 第一步:模糊请求
你: 我需要一个用户登录功能
# Claude提问澄清
Claude: 需要哪种登录方式?
- Email + Password
- OAuth (Google, GitHub)
- Phone + SMS
# 第二步:明确需求
你: 使用Email和Password登录
# Claude设计方案
Claude: 我建议使用以下技术栈:
- 前端表单验证
- JWT token认证
- bcrypt加密密码
是否同意?
# 第三步:确认方案
你: 同意,开始实现
# 第四步:迭代完善
你: 添加"记住我"功能
你: 添加邮箱验证功能
技巧6: 建立錯誤處理模式
在CLAUDE.md中定義標準的錯誤處理模式:
## Error Handling Patterns
### API Errors
```typescript
// All API calls should use this pattern
try {
const response = await api_call();
return response.data;
} catch (error) {
if (error.response?.status === 401) {
// Handle unauthorized
redirectToLogin();
} else if (error.response?.status === 404) {
// Handle not found
showNotFoundError();
} else {
// Handle other errors
showGenericError(error.message);
}
throw error; // Re-throw for caller to handle
}
Form Validation Errors
// Always validate user input
const validateEmail = (email: string): boolean => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
if (!validateEmail(userInput.email)) {
throw new ValidationError('Invalid email format');
}
Database Errors
// Handle database connection errors
try {
await db.connect();
} catch (error) {
logger.error('Database connection failed', error);
// Retry logic
await retryConnection();
}
## 常見問題解答(FAQ)
### Q1: Claude Code和ChatGPT/Cursor有什麼區別?
**A:**
```markdown
Claude Code的独特优势:
1. **命令行集成**:直接在终端中使用,不需要切换窗口
2. **Agent模式**:可以自主执行多步骤任务
3. **CLAUDE.md**:项目级上下文配置,持续记住项目规范
4. **MCP支持**:可扩展的工具集成,连接外部系统
5. **Unix哲学**:可组合、可脚本化,适合CI/CD集成
相比ChatGPT:
- 更适合编程任务
- 可以直接操作文件系统
- 专注开发场景
相比Cursor:
- 更灵活的命令行界面
- 更强的自定义能力
- 可与其他CLI工具组合
Q2: 如何提高Claude Code的準確性?
A:
提高准确性的5个方法:
1. **完善CLAUDE.md**
- 详细的项目规范
- 代码示例
- 常见模式
- 禁止事项
2. **精确的提示词**
- 具体明确的需求
- 文件路径和行号
- 代码示例
- 约束条件
3. **分步处理**
- 拆分复杂任务
- 每步验证结果
- 及时反馈调整
4. **利用上下文**
- 引用现有代码
- 参考成功案例
- 保持对话连贯
5. **建立测试**
- 编写测试用例
- 自动验证结果
- 发现问题及时纠正
Q3: Claude Code會洩露我的程式碼嗎?
A:
隐私和安全:
✅ **安全措施**:
- 代码仅在处理时使用
- 不会用于训练其他模型
- 企业级安全保障
- SOC 2 Type II认证
✅ **数据保护**:
- 加密传输和存储
- 访问控制
- 审计日志
- 数据保留政策
⚠️ **注意事项**:
- 不要提交敏感信息(API密钥、密码)
- 使用.env文件管理密钥
- 定期审查访问日志
- 了解企业数据政策
📖 **详细隐私政策**:
https://www.anthropic.com/privacy
Q4: 可以在離線環境使用Claude Code嗎?
A:
离线使用限制:
❌ **不能离线使用的原因**:
- 需要连接Claude API
- 实时代码分析和生成
- 模型推理在云端进行
⚠️ **部分解决方案**:
1. 使用本地缓存
- 缓存常用代码片段
- 保存常用命令
2. 准备离线文档
- 项目规范文档
- 代码模板
- 常见问题手册
3. 考虑本地模型(功能受限)
- 使用本地运行的开源模型
- 功能会有较大限制
- 不推荐作为主要方案
✅ **推荐做法**:
- 确保稳定的网络连接
- 使用网络代理(如果需要)
- 准备备用方案
Q5: 如何處理Claude Code的計費?
A:
成本优化策略:
💰 **计费方式**:
- 按Token使用量计费
- 输入和输出分别计费
- 不同模型价格不同
💡 **节省成本的方法**:
1. **优化提示词**
- 简洁明确的要求
- 避免重复上下文
- 使用CLAUDE.md减少重复
2. **减少Token使用**
- 只读取必要文件
- 使用搜索代替全读
- 分段处理大文件
3. **选择合适模型**
- 简单任务用小模型
- 复杂任务用大模型
- 根据预算选择
4. **使用缓存**
- 缓存常用代码
- 复用之前结果
- 避免重复生成
5. **监控使用量**
- 定期检查API使用
- 设置使用限额
- 分析使用模式
📊 **成本估算**:
- 小型项目: ~$10-50/月
- 中型项目: ~$50-200/月
- 大型项目: ~$200-500/月
Q6: Claude Code支援哪些程式語言?
A:
语言支持范围:
✅ **完全支持**:
- JavaScript/TypeScript (最佳支持)
- Python
- Java
- Go
- Rust
- C/C++
- Ruby
- PHP
- Swift
- Kotlin
✅ **良好支持**:
- 所有主流编程语言
- 标记语言(HTML, CSS, Markdown)
- 配置语言(JSON, YAML, TOML)
- Shell脚本(Bash, Zsh)
⚠️ **支持较弱**:
- 非主流语言
- 特定领域语言(DSL)
- 某些汇编语言
💡 **使用建议**:
1. 确保项目文件能被正确识别
2. 在CLAUDE.md中声明语言特性
3. 提供代码示例供参考
4. 明确语言特定的规范
Q7: 如何處理大型專案?
A:
大型项目策略:
📁 **项目组织**:
1. 模块化CLAUDE.md
```markdown
# 主配置檔案
## Project Overview
## Tech Stack
# 引入子模組
See: `docs/CLAUDE-backend.md`
See: `docs/CLAUDE-frontend.md`
- 分层配置
- 项目级:通用规范
- 模块级:特定规范
- 目录级:本地规范
🔍 搜索策略:
## Search Scope for Large Projects
### Priority Order
1. Current module: `src/modules/[current-module]/`
2. Related modules: `src/modules/`
3. Shared code: `src/common/`
4. Core: `src/core/`
### Search Limits
- Maximum files: 50
- Maximum depth: 5 directories
- Ignore: node_modules, build, dist
🚀 分阶段处理:
## Large Project Workflow
### Phase 1: Understanding
- Read architecture docs
- Identify main modules
- Understand data flow
### Phase 2: Planning
- Create task list
- Prioritize by impact
- Estimate complexity
### Phase 3: Execution
- Work on one module at a time
- Test incrementally
- Document changes
### Phase 4: Integration
- Update cross-module references
- Run full test suite
- Update documentation
Q8: 遇到bug怎么办?
A:
Bug處理流程:
🐛 **第一步:收集資訊**
```bash
# 错误详情
- 完整的错误消息
- 错误堆栈
- 复现步骤
- 预期行为 vs 实际行为
# 环境信息
- Claude Code版本
- 操作系统
- Node.js/Python版本
- 项目配置
🔧 第二步:嘗試解決
# 常用解决方案
1. 重启Claude Code
exit && claude
2. 清除缓存
claude --clear-cache
3. 重新认证
claude auth logout
claude auth login
4. 检查更新
claude --update
📝 第三步:報告問題
如果问题持续:
1. 搜索已知问题
https://github.com/anthropics/claude-code/issues
2. 创建问题报告
- 标题:简洁描述问题
- 描述:详细复现步骤
- 证据:错误消息、日志
- 环境:系统信息
- 标签:bug, [相关领域]
3. 联系支持
support@anthropic.com
Q9: 可以多個專案共用一個CLAUDE.md嗎?
A:
多项目策略:
❌ **不推荐**共用CLAUDE.md:
- 每个项目有不同的规范
- 配置混杂会降低准确性
- 难以维护
✅ **推荐的方案**:
1. **使用模板**
```bash
# 建立通用模板
~/.claude/templates/web-app.md
~/.claude/templates/api-service.md
~/.claude/templates/cli-tool.md
-
继承配置
# 子專案CLAUDE.md
# 繼承父專案配置
Inherits: ../CLAUDE.md
# 新增特定配置
Overrides:
- Custom modules
- Specific conventions -
使用符号链接(谨慎)
# 僅適用於規範完全相同的子專案
ln -s ../CLAUDE.md ./CLAUDE.md -
模块化配置
# 主配置
## Common Standards
- Coding style: Airbnb
- Linter: ESLint
- Formatter: Prettier
# 專案特定
## Project Specific
See: `docs/standards.md`
Q10: Claude Code会取代程序员吗?
A:
人機協作的未來:
🤝 **Claude Code的定位**:
- **輔助工具**,不是替代者
- 增強能力,不是削弱價值
- 提高效率,不是減少需求
✅ **Claude Code擅長的**:
- 重複性編碼任務
- 程式碼重構和格式化
- 查詢和修復bug
- 程式碼文件生成
- 技術調研和學習
✅ **程式設計師擅長的**:
- 需求分析和設計
- 架構決策
- 創造性解決問題
- 業務理解
- 團隊協作
- 複雜系統設計
💡 **未來的工作模式**:
程序员 + Claude Code = 超级程序员
- 程序员:提出问题、设计解决方案、审核代码
- Claude Code:实现细节、执行任务、提供选项
🎯 **建議**:
1. 擁抱AI工具,而不是抗拒
2. 專注於高價值的創造性工作
3. 學習如何更好地使用AI工具
4. 培養系統思維和架構能力
5. 保持學習和適應能力
📚 **相關閱讀**:
- [AI Augmented Programming](https://www.anthropic.com/index/ai-augmented-programming)
- [Future of Software Development](https://claude.com/blog/future-of-coding)
總結
透過本文的系統性介紹,你現在應該能夠:
✅ 快速診斷問題: 用系統化的排查流程
✅ 解決常見問題: 命令不生效、輸出不符預期、檔案操作失敗等
✅ 最佳化效能: 提高響應速度、減少Token使用、處理大型專案
✅ 預防問題: 建立好的配置、使用模板、分階段處理
✅ 獲取幫助: 知道何時以及如何報告問題
關鍵要點
-
好的配置是成功的一半
- 投時間完善CLAUDE.md
- 明確專案規範和約束
- 提供程式碼示例和模板
-
精確溝通至關重要
- 具體明確的指令
- 提供上下文和示例
- 分步處理複雜任務
-
系統化排查方法
- 按步驟診斷問題
- 收集詳細資訊
- 嘗試標準解決方案
-
持續最佳化和改進
- 記錄常見問題
- 建立最佳實踐
- 分享經驗教訓
-
人機協作思維
- Claude是助手,不是替代者
- 保持批判性思維
- 學會驗證和審查
下一步
- 實踐: 在實際專案中應用這些解決方案
- 定製: 根據專案特點定製CLAUDE.md
- 分享: 將遇到的新問題和解決方案加入本文件
- 學習: 探索更多高階特性和最佳實踐
參考資源
記住:遇到問題不要慌張,大多數問題都有明確的解決方法。關鍵是保持冷靜,系統化地排查,並善用本文提供的解決方案。
Sources: