跳至主要内容

錯誤資訊解讀

在使用Claude Code的過程中,遇到錯誤是不可避免的。無論是認證失敗、網路超時、許可權問題,還是API錯誤,這些錯誤資訊雖然看起來晦澀難懂,但它們實際上包含了寶貴的問題診斷資訊。

本文將系統地解讀Claude Code的各類錯誤資訊,幫助你快速定位問題根源,找到正確的解決方案,讓AI程式設計助手真正成為可靠的開發夥伴。

理解錯誤資訊的結構

錯誤資訊的基本組成

Claude Code的錯誤資訊通常包含以下幾個關鍵部分:

错误类型错误消息: 详细描述
at 文件名:行号
at 函数名 (文件:行号)

示例分析:

Error: Authentication failed
at ClaudeAPI.authenticate (/usr/local/lib/node_modules/claude-code/dist/api.js:45:12)
at async main (/usr/local/lib/node_modules/claude-code/dist/index.js:120:5)

解讀方法:

  1. 錯誤型別 (Error): 說明錯誤的類別
  2. 錯誤訊息 (Authentication failed): 具體的問題描述
  3. 錯誤位置 (api.js:45:12): 發生錯誤的檔案和行號
  4. 呼叫棧 (at main): 錯誤發生的呼叫鏈

常見錯誤型別分類

Claude Code的錯誤可以分為以下幾大類:

1. 認證和授權錯誤

  • AuthenticationError: 認證失敗
  • AuthorizationError: 許可權不足
  • TokenError: Token過期或無效

2. 網路錯誤

  • NetworkError: 網路連線問題
  • TimeoutError: 請求超時
  • ConnectionRefusedError: 連線被拒絕

3. API錯誤

  • RateLimitError: 超出API速率限制
  • QuotaError: 配額用盡
  • InvalidRequestError: 請求無效

4. 檔案系統錯誤

  • FileNotFoundError: 檔案未找到
  • PermissionError: 許可權不足
  • ValidationError: 資料驗證失敗

認證和授權錯誤

錯誤1: Authentication failed

完整錯誤資訊:

Error: Authentication failed: Invalid API key
at ClaudeAPI.validateCredentials (/usr/local/lib/node_modules/claude-code/dist/auth.js:234:15)

錯誤含義:

Claude Code無法驗證你的身份,通常是因為API金鑰無效或缺失。

可能原因:

  1. API金鑰未設定或設定錯誤
  2. API金鑰已過期
  3. API金鑰被撤銷
  4. 認證配置檔案損壞

解決方案:

方案1: 重新認證

# 退出当前登录
claude auth logout

# 重新登录
claude auth login

# 按照提示完成认证流程
# 系统会打开浏览器进行授权

方案2: 檢查API金鑰

# 查看当前认证状态
claude auth status

# 输出示例:
# ✓ Logged in as user@example.com
# ✓ API key: sk-ant-...xxxx (valid)
# ✗ API quota: 0/100000 used

# 如果显示无效,需要更新密钥

方案3: 手動設定API金鑰

# 设置环境变量
export ANTHROPIC_API_KEY="your-api-key-here"

# 或者在~/.bashrc或~/.zshrc中添加
echo 'export ANTHROPIC_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc

方案4: 檢查金鑰許可權

# 确保密钥文件权限正确
ls -la ~/.claude/

# 如果权限不对,修复权限
chmod 600 ~/.claude/api-key
chmod 700 ~/.claude/

預防措施:

## Authentication Maintenance

### Regular Tasks
- Check auth status weekly: `claude auth status`
- Rotate API keys every 90 days
- Monitor API quota usage
- Keep backup of valid keys

### Security Best Practices
- Never commit API keys to git
- Use environment variables for keys
- Rotate keys periodically
- Monitor usage for anomalies

錯誤2: Authorization required

完整錯誤資訊:

Error: Authorization required: Insufficient permissions for this operation
at ClaudeAPI.checkPermission (/usr/local/lib/node_modules/claude-code/dist/api.js:189:11)

錯誤含義:

你的賬戶已認證,但沒有執行特定操作的許可權。

可能原因:

  1. API金鑰許可權不足
  2. 企業賬戶許可權限制
  3. 超出使用限額
  4. 功能需要付費訂閱

解決方案:

方案1: 檢查賬戶許可權

# 登录Claude.ai检查账户状态
# 访问: https://claude.ai/account

# 检查以下内容:
# - 订阅类型 (Free/Pro/Team)
# - API权限范围
# - 使用限额
# - 账户状态 (正常/暂停)

方案2: 升級訂閱計劃

# 如果需要更多功能,考虑升级
# Free计划限制:
# - 每日请求限制
# - 基础功能访问
# - 标准响应速度

# Pro计划优势:
# - 更高的请求限额
# - 优先响应速度
# - 高级功能访问
# - 更长的上下文窗口

方案3: 使用企業賬戶

## Enterprise Setup

If using Claude Code for work:

1. **Use enterprise credentials**
```bash
claude auth login --enterprise
  1. Configure enterprise settings

    # Create ~/.claude/enterprise-config.json
    {
    "organization": "your-company",
    "team": "your-team",
    "policy": "enterprise-policy"
    }
  2. Verify permissions

    • Check with IT administrator
    • Ensure IP allowlisting
    • Verify SSO integration

### 錯誤3: Token expired

**完整錯誤資訊:**

```bash
Error: Token expired: Please refresh your authentication token
at SessionManager.validateToken (/usr/local/lib/node_modules/claude-code/dist/session.js:98:13)

錯誤含義:

你的認證令牌已過期,需要重新整理。

解決方案:

# 快速刷新令牌
claude auth refresh

# 如果refresh不工作,重新登录
claude auth logout
claude auth login

自動令牌管理:

## Token Management in CLAUDE.md

```markdown
## Authentication Auto-Refresh

### Token Policy
- Auto-refresh tokens before expiration
- Warn user 7 days before expiry
- Cache tokens securely

### Implementation
When authentication errors occur:
1. Try to auto-refresh token
2. If refresh fails, prompt user to re-login
3. Show clear error messages
4. Provide login command instructions

网络错误

错误4: Network timeout

完整错误信息:

Error: Network timeout: Request timed out after 30000ms
at APIClient.request (/usr/local/lib/node_modules/claude-code/dist/network.js:156:19)

错误含义:

Claude Code无法在指定时间内连接到API服务器。

可能原因:

  1. 网络连接不稳定
  2. 防火墙阻止连接
  3. API服务器响应慢
  4. 代理配置错误
  5. DNS解析问题

解决方案:

方案1: 检查网络连接

# 測試基本連線
ping -c 3 claude.ai

# 測試HTTPS連線
curl -I https://claude.ai

# 測試API端點
curl -I https://api.anthropic.com

# 預期輸出: HTTP/1.1 200 OK 或 HTTP/2 200

方案2: 配置代理

# 如果需要使用代理,設定代理環境變數
export HTTP_PROXY="http://proxy.example.com:8080"
export HTTPS_PROXY="http://proxy.example.com:8080"
export NO_PROXY="localhost,127.0.0.1,.local"

# 測試代理連線
curl -x http://proxy.example.com:8080 -I https://claude.ai

# 或者在CLAUDE.md中配置
# Claude會自動使用這些設定

方案3: 增加超时时间

# 臨時增加超時時間
claude --timeout 60000 # 60秒

# 或者配置在環境變數中
export CLAUDE_TIMEOUT=60000

方案4: 检查DNS解析

# 測試DNS解析
nslookup claude.ai
dig claude.ai

# 如果DNS有問題,嘗試使用公共DNS
# macOS
sudo networksetup -setdnsservers Wi-Fi 8.8.8.8 8.8.4.4

# Linux
echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf

方案5: 检查防火墙

# macOS
# 檢查防火牆狀態
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate

# 臨時關閉防火牆測試
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off

# Linux
sudo ufw status
sudo iptables -L

# Windows
netsh advfirewall show allprofiles

网络诊断脚本:

#!/bin/bash
# network-diagnostic.sh

echo "=== Claude Code Network Diagnostic ==="
echo ""

echo "1. Testing basic connectivity..."
ping -c 3 claude.ai

echo ""
echo "2. Testing HTTPS connection..."
curl -I https://claude.ai

echo ""
echo "3. Testing API endpoint..."
curl -I https://api.anthropic.com

echo ""
echo "4. Checking DNS..."
nslookup claude.ai

echo ""
echo "5. Checking proxy settings..."
echo "HTTP_PROXY: $HTTP_PROXY"
echo "HTTPS_PROXY: $HTTPS_PROXY"

echo ""
echo "6. Testing timeout..."
time curl -m 10 https://claude.ai

echo ""
echo "=== Diagnostic Complete ==="

错误5: Connection refused

完整错误信息:

Error: Connection refused: Unable to connect to api.anthropic.com:443
at NetworkLayer.connect (/usr/local/lib/node_modules/claude-code/dist/network.js:78:11)

错误含义:

系统拒绝了与API服务器的连接。

可能原因:

  1. 端口被阻止
  2. SSL/TLS证书问题
  3. 企业网络策略限制
  4. VPN干扰

解决方案:

方案1: 检查端口访问

# 測試443埠(HTTPS)
telnet api.anthropic.com 443

# 或使用nc (netcat)
nc -zv api.anthropic.com 443

# 預期輸出:
# Connection to api.anthropic.com 443 port [tcp/https] succeeded!

方案2: 检查SSL证书

# 測試SSL連線
openssl s_client -connect api.anthropic.com:443

# 檢查證書資訊
openssl s_client -connect api.anthropic.com:443 -servername api.anthropic.com | openssl x509 -noout -dates

# 如果證書有問題,更新系統證書
# macOS
sudo softwareupdate --install-certs

# Linux (Ubuntu/Debian)
sudo update-ca-certificates

# Linux (CentOS/RHEL)
sudo update-ca-trust

方案3: 检查VPN设置

# 如果使用VPN,嘗試斷開
# 某些VPN會阻止API訪問

# 或配置VPN分流
# 讓claude.ai走直連,其他流量走VPN

# macOS
# 在VPN設定中配置Split Tunneling

# Linux
# 使用routing rules配置特定路由
ip route add api.anthropic.com via $GATEWAY dev $INTERFACE

方案4: 企业网络配置

## Corporate Network Setup

If working in a corporate environment:

### 1. Firewall Whitelist
Request IT to whitelist:
- `api.anthropic.com:443`
- `claude.ai:443`

### 2. Proxy Configuration
```bash
# Configure enterprise proxy
export HTTP_PROXY="http://corporate-proxy:8080"
export HTTPS_PROXY="http://corporate-proxy:8080"

3. SSL Inspection

If SSL inspection is enabled:

  • Request certificate exception
  • Configure custom CA certificates
  • Use enterprise-specific endpoints

4. VPN Requirements

  • Use approved VPN client
  • Configure split tunneling
  • Add domains to bypass list

### 错误6: DNS resolution failed

**完整错误信息:**

```bash
Error: DNS resolution failed: Unable to resolve api.anthropic.com
at DNSResolver.lookup (/usr/local/lib/node_modules/claude-code/dist/dns.js:45:13)

解决方案:

# 方案1: 重新整理DNS快取
# macOS
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

# Linux
sudo systemd-resolve --flush-caches
# 或
sudo service dnsmasq restart

# Windows
ipconfig /flushdns

# 方案2: 更換DNS伺服器
# 使用Google DNS (8.8.8.8, 8.8.4.4)
# 使用Cloudflare DNS (1.1.1.1, 1.0.0.1)

# macOS
sudo networksetup -setdnsservers Wi-Fi 8.8.8.8 8.8.4.4

# Linux (永久)
sudo nano /etc/systemd/resolved.conf
# 取消註釋並設定:
# DNS=8.8.8.8 8.8.4.4
sudo systemctl restart systemd-resolved

# 方案3: 新增到hosts檔案(臨時)
echo "160.79.104.9 api.anthropic.com" | sudo tee -a /etc/hosts

API错误

错误7: Rate limit exceeded

完整错误信息:

Error: Rate limit exceeded: Too many requests. Please try again later.
at RateLimiter.checkLimit (/usr/local/lib/node_modules/claude-code/dist/ratelimit.js:123:15)

Details:
- Limit: 50 requests per 10 seconds
- Current: 55 requests
- Retry after: 5 seconds

错误含义:

你在短时间内发送了太多请求,超出了API的速率限制。

可能原因:

  1. 批量操作未限速
  2. 循环中调用API
  3. 多个实例同时运行
  4. 自动化脚本过于频繁

解决方案:

方案1: 等待并重试

# 錯誤資訊會告訴你需要等待多久
# 上面示例顯示需要等待5秒

# 使用指數退避策略
# 第一次失敗: 等待5秒
# 第二次失敗: 等待10秒
# 第三次失敗: 等待20秒

方案2: 实现速率限制

## Rate Limiting in CLAUDE.md

```markdown
## API Rate Limiting

### Rate Limits
- Free tier: 50 requests / 10 seconds
- Pro tier: 100 requests / 10 seconds
- Team tier: Custom limits

### When Making Multiple Requests
- Space out requests by at least 200ms
- Use batching when possible
- Implement exponential backoff on errors
- Cache responses to avoid duplicate requests

### Batch Operation Pattern
When processing multiple items:
```bash
# Process in batches of 10
for batch in $(seq 1 10); do
# Process 10 items
# Wait 2 seconds between batches
sleep 2
done

Error Handling

If rate limit error occurs:

  1. Extract "Retry-After" time from error
  2. Wait for specified duration
  3. Retry the request
  4. If still failing, wait longer and try again

#### 方案3: 使用批次處理

```bash
# 不好的做法: 逐个处理
for file in *.js; do
claude "analyze $file" # 每个文件一次请求
done

# 好的做法: 批量处理
claude "Analyze all JavaScript files in the current directory.
Focus on: $(ls *.js | tr '\n' ' ')"

# 或者分批处理
files=($(ls *.js))
batch_size=10

for ((i=0; i<${#files[@]}; i+=batch_size)); do
batch=("${files[@]:i:batch_size}")
claude "Analyze these files: ${batch[*]}"
sleep 2 # 批次之间等待
done

錯誤8: Quota exceeded

完整錯誤資訊:

Error: Quota exceeded: Monthly token quota exceeded
at QuotaManager.checkQuota (/usr/local/lib/node_modules/claude-code/dist/quota.js:67:11)

Details:
- Monthly quota: 100,000 tokens
- Used: 100,543 tokens
- Over: 543 tokens
- Resets: 2024-02-01

錯誤含義:

你已經用完了當月的API配額。

解決方案:

方案1: 等待配額重置

# 查看重置日期
# 上面示例显示配额在2024-02-01重置

# 在重置之前,只能等待
# 或者升级到更高配额的计划

方案2: 最佳化Token使用

## Token Optimization Strategy

### Reduce Input Tokens
1. **Be concise in prompts**
```bash
# 不好的做法: 冗長的提示
你: 我想請你幫我分析一下這個JavaScript檔案的內容,
這個檔案位於src/utils/helpers.js,請你詳細地告訴我...

# 好的做法: 簡潔的提示
你: 分析 src/utils/helpers.js
  1. Use CLAUDE.md for context

    # 將專案資訊放在CLAUDE.md中
    # 避免每次對話重複說明
    ## Project Context
    - Framework: React + TypeScript
    - Style: Functional components
    - Testing: Jest
  2. Read only necessary files

    # 不好的做法
    你: 讀取所有配置檔案

    # 好的做法
    你: 只讀取package.json,不讀取其他配置檔案

Reduce Output Tokens

  1. Request specific format

    # 請求簡潔的輸出
    你: 只輸出修改後的程式碼,不需要解釋

    # 或請求特定格式
    你: 用JSON格式輸出結果
  2. Limit response length

    你: 總結不超過3句話

    你: 列出前5個問題即可

Monitor Usage

# 定期檢查使用情況
claude usage

# 輸出示例:
# Period: 2024-01-01 to 2024-01-31
# Used: 85,432 / 100,000 tokens (85%)
# Remaining: 14,568 tokens
# Projected usage: 105,000 (will exceed!)

方案3: 升级订阅计划

## Plan Comparison

### Free Plan
- 100K tokens/month
- Standard response time
- Community support

### Pro Plan ($20/month)
- 1M tokens/month (10x)
- Priority response time
- Email support
- Early access features

### Team Plan (Custom)
- Unlimited tokens
- Dedicated support
- Custom integrations
- SLA guarantee

### Upgrade Decision Tree

Current usage < 80K/month → Stay on Free Current usage 80K-500K/month → Upgrade to Pro Current usage > 500K/month → Consider Team


### 錯誤9: Invalid request

**完整錯誤資訊:**

```bash
Error: Invalid request: Malformed request body
at RequestValidator.validate (/usr/local/lib/node_modules/claude-code/dist/validation.js:89:14)

Details:
- Field: "messages"
- Issue: "Array cannot be empty"
- Request ID: req_abc123xyz

錯誤含義:

傳送給API的請求格式不正確或包含無效資料。

可能原因:

  1. 請求引數格式錯誤
  2. 必需欄位缺失
  3. 資料型別不匹配
  4. 引數值超出範圍

解決方案:

方案1: 檢查請求格式

# 如果是手动调用API,检查请求格式
# 标准格式应该如下:

{
"model": "claude-3-5-sonnet-20241022",
"messages": [
{
"role": "user",
"content": "Your message here"
}
],
"max_tokens": 1024
}

方案2: 驗證引數

## Common Invalid Request Issues

### Empty Messages
❌ Wrong:
```json
{
"messages": []
}

✅ Correct:

{
"messages": [
{"role": "user", "content": "Hello"}
]
}

Invalid max_tokens

❌ Wrong:

{
"max_tokens": -1
}

✅ Correct:

{
"max_tokens": 4096
}

Invalid Temperature

❌ Wrong:

{
"temperature": 2.5 // Must be 0-1
}

✅ Correct:

{
"temperature": 0.7
}

#### 方案3: 檢視詳細錯誤

```bash
# 启用详细模式查看完整错误
claude --verbose

# 或查看日志
tail -f ~/.claude/logs/claude-code.log

# 查找"validation"或"invalid"关键词
grep -i "invalid" ~/.claude/logs/claude-code.log

檔案系統錯誤

錯誤10: File not found

完整錯誤資訊:

Error: File not found: /path/to/project/src/components/Button.js
at FileSystem.readFile (/usr/local/lib/node_modules/claude-code/dist/fs.js:234:11)

錯誤含義:

Claude Code無法找到指定的檔案。

可能原因:

  1. 檔案路徑錯誤
  2. 檔案尚未建立
  3. 工作目錄不正確
  4. 符號連結斷裂
  5. 檔案被刪除

解決方案:

方案1: 驗證檔案路徑

# 检查文件是否存在
test -f /path/to/file.js && echo "Exists" || echo "Not found"

# 或使用ls
ls -la /path/to/project/src/components/Button.js

# 查找相似的文件
find /path/to/project -name "Button.js" -o -name "button.js"

# 搜索包含Button的文件
find /path/to/project -name "*[Bb]utton*"

方案2: 使用相對路徑

# 检查当前工作目录
pwd

# 使用相对路径
./src/components/Button.js

# 或使用..引用父目录
../components/Button.js

方案3: 檢查檔案許可權

# 检查文件权限
ls -la file.js

# 输出示例:
# -rw-r--r-- 1 user group 1234 Jan 1 12:00 file.js
# ^^^
# |||
# ||| 其他用户权限
# || 组权限
# | 所有者权限
# 文件类型

# 如果权限错误,修复权限
chmod 644 file.js # 普通文件
chmod 755 script.sh # 可执行文件

方案4: 在CLAUDE.md中配置路徑

## File Path Resolution

### Project Root
Always assume we're working in: `/Users/username/projects/my-project`

### Common Locations
- Components: `src/components/`
- Utils: `src/utils/`
- Tests: `tests/`
- Config: `config/`

### Path Resolution Rules
1. If I provide relative path, it's relative to project root
2. Always verify file exists before reading
3. If file not found, search in common locations
4. Use absolute paths when unsure

錯誤11: Permission denied

完整錯誤資訊:

Error: Permission denied: Unable to write to /path/to/file.js
at FileSystem.writeFile (/usr/local/lib/node_modules/claude-code/dist/fs.js:178:13)

Details:
- Required permissions: read, write
- Current permissions: read-only
- File owner: root
- Current user: john

錯誤含義:

你沒有許可權執行該檔案操作。

可能原因:

  1. 檔案屬於其他使用者
  2. 檔案是隻讀的
  3. 目錄沒有寫許可權
  4. 需要管理員許可權

解決方案:

方案1: 修改檔案許可權

# 查看文件权限
ls -la file.js

# 修改权限
chmod u+w file.js # 给所有者添加写权限
chmod 664 file.js # 设置为rw-rw-r--
chmod +w file.js # 添加写权限

# 修改所有者
sudo chown $USER:$USER file.js

方案2: 檢查目錄許可權

# 检查目录权限
ls -la /path/to/directory/

# 如果目录没有写权限,修改目录权限
chmod u+w /path/to/directory/

# 递归修改整个目录树
chmod -R u+w /path/to/directory/

方案3: 使用sudo(謹慎)

# 只有在必要时使用sudo
# 谨慎: sudo会以root权限执行命令

sudo vi file.js
# 或
sudo chmod 666 file.js

安全提示:

## Permission Management Best Practices

### Avoid Using Sudo
❌ Don't:
```bash
sudo claude # 以root執行Claude Code

✅ Do:

# Fix permissions instead
sudo chown -R $USER:$USER ~/.claude/
chmod -R 755 ~/.claude/

Project Permissions

Ensure project files are owned by you:

# Fix project ownership
sudo chown -R $USER:$USER /path/to/project/

# Set appropriate permissions
find /path/to/project/ -type f -exec chmod 644 {} \;
find /path/to/project/ -type d -exec chmod 755 {} \;
find /path/to/project/ -name "*.sh" -exec chmod 755 {} \;

Git Repository Permissions

# Fix git repository permissions
cd /path/to/repo
sudo chown -R $USER:$USER .git/
chmod -R u+rw .git/

Claude Code Directory

# Ensure Claude Code can manage its own directory
sudo chown -R $USER:$USER ~/.claude/
chmod -R 700 ~/.claude/ # Only owner can access

配置错误

错误12: Invalid configuration

完整错误信息:

Error: Invalid configuration: Unknown option "enableBeta"
at ConfigLoader.load (/usr/local/lib/node_modules/claude-code/dist/config.js:145:17)

File: ~/.claude/config.json
Line: 15
Position: 5

错误含义:

Claude Code的配置文件包含无效的配置选项。

解决方案:

方案1: 验证配置文件

# 檢視配置檔案
cat ~/.claude/config.json

# 檢查JSON語法
python3 -m json.tool ~/.claude/config.json

# 或使用jq
jq '.' ~/.claude/config.json

方案2: 重置配置

# 備份當前配置
cp ~/.claude/config.json ~/.claude/config.json.backup

# 刪除或重新命名配置檔案
mv ~/.claude/config.json ~/.claude/config.json.old

# 重新初始化
claude --init

# 或手動建立預設配置
cat > ~/.claude/config.json << 'EOF'
{
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.7,
"maxTokens": 4096
}
EOF

方案3: 查看可用配置选项

# 檢視幫助文件
claude --help

# 或檢視配置文件
claude config --schema

# 輸出示例:
# {
# "$schema": "http://json-schema.org/draft-07/schema#",
# "type": "object",
# "properties": {
# "model": { "type": "string" },
# "temperature": { "type": "number", "minimum": 0, "maximum": 1 },
# "maxTokens": { "type": "number", "minimum": 1 }
# }
# }

推荐配置:

## Claude Code Configuration Template

### ~/.claude/config.json
```json
{
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.7,
"maxTokens": 4096,
"timeout": 30000,
"retry": {
"maxAttempts": 3,
"backoff": "exponential"
},
"logging": {
"level": "info",
"file": "~/.claude/logs/claude.log"
},
"features": {
"autoSave": true,
"gitIntegration": true,
"syntaxHighlighting": true
}
}

Project-specific config (.claude/config.json)

{
"extends": "../default-config.json",
"temperature": 0.5,
"maxTokens": 2048,
"projectSettings": {
"language": "typescript",
"framework": "react",
"testRunner": "jest"
}
}

### 错误13: CLAUDE.md syntax error

**完整错误信息:**

```bash
Warning: CLAUDE.md parsing error at line 45
Error: Unclosed code block
at MarkdownParser.parse (/usr/local/lib/node_modules/claude-code/dist/markdown.js:78:11)

File: ./CLAUDE.md
Line: 45
Context: Unexpected end of file while parsing code block

错误含义:

CLAUDE.md文件包含Markdown语法错误。

解决方案:

方案1: 检查Markdown语法

# 常見錯誤1: 未閉合的程式碼塊
❌ Wrong:
```markdown
## Code Example
```javascript
function hello() {
console.log("hello");
# 缺少結束的```

✅ Correct:
```markdown
## Code Example
```javascript
function hello() {
console.log("hello");
}

# 常见错误2: 未闭合的列表
❌ Wrong:
```markdown
## Items
- Item 1
- Item 2
- Nested item
# 缺少父列表的閉合

✅ Correct:

## Items
- Item 1
- Item 2
- Nested item

#### 方案2: 使用Markdown驗證工具

```bash
# 使用markdownlint
npm install -g markdownlint-cli

# 检查CLAUDE.md
markdownlint CLAUDE.md

# 自动修复
markdownlint --fix CLAUDE.md

# 或使用VS Code扩展
# code --install-extension DavidAnson.vscode-markdownlint

方案3: 分段測試

# 如果CLAUDE.md很大,分段测试
# 先测试前100行
head -n 100 CLAUDE.md > test-claude.md
markdownlint test-claude.md

# 逐步增加行数,定位错误位置
head -n 200 CLAUDE.md > test-claude.md
markdownlint test-claude.md

# 继续直到发现错误
head -n 300 CLAUDE.md > test-claude.md
markdownlint test-claude.md

CLAUDE.md最佳實踐:

## CLAUDE.md Template and Guidelines

### Basic Structure
```markdown
# Project Name

## Overview
[Brief project description]

## Technology Stack
- Framework: ...
- Language: ...
- Tools: ...

## Directory Structure

src/ ├── components/ ├── utils/ └── styles/


## Coding Conventions
[Style guidelines]

## Common Commands
```bash
npm run dev
npm run build

Common Pitfalls

⚠️ [Things to avoid]


### Markdown Syntax Rules

1. **Code Blocks**
- Always close with ```
- Specify language for syntax highlighting
- Don't nest code blocks

2. **Lists**
- Use consistent indentation (2 spaces)
- Don't mix numbered and bulleted lists
- Leave blank line before and after lists

3. **Headings**
- Use # for main title
- Use ## for sections
- Don't skip levels (### after #)

4. **Links**
- Use [text](url) format
- Escape URLs with special characters

5. **Special Characters**
- Escape * _ [ ] ( ) with backslash in plain text
- No need to escape inside code blocks

实用错误排查技巧

技巧1: 系统化排查流程

当遇到错误时,按照以下步骤系统化地排查:

第一步: 读取完整错误信息

# 不要只看第一行
# 讀取完整的錯誤堆疊

# 使用詳細模式
claude --verbose 2>&1 | tee error.log

# 檢視錯誤日誌
cat ~/.claude/logs/latest.log

第二步: 识别错误类型

# 判斷錯誤類別
# - 認證錯誤? → 檢查API金鑰
# - 網路錯誤? → 檢查網路連線
# - 許可權錯誤? → 檢查檔案許可權
# - 配置錯誤? → 檢查配置檔案
# - API錯誤? → 檢查請求格式

第三步: 复现错误

# 嘗試復現錯誤
# 記錄復現步驟

# 示例:
1. 執行: claude "測試"
2. 結果: Authentication failed
3. 環境: macOS 14.0
4. 網路: 公司VPN
5. 配置: 使用預設配置

第四步: 隔离问题

# 在不同環境中測試
# 確定是環境問題還是普遍問題

# 測試1: 簡單命令
echo "hello" | claude

# 測試2: 不同網路
# 斷開VPN重試
# 使用手機熱點重試

# 測試3: 不同專案
# 在新目錄中建立測試專案
mkdir /tmp/test-claude
cd /tmp/test-claude
claude "建立一個hello.js檔案"

第五步: 查找解决方案

# 搜尋已知問題
# GitHub Issues
https://github.com/anthropics/claude-code/issues

# 官方文件
https://docs.anthropic.com/claude/docs/claude-code

# 社羣論壇
https://community.anthropic.com

技巧2: 使用调试模式

# 啟用詳細日誌
export CLAUDE_DEBUG=1
export CLAUDE_LOG_LEVEL=debug

# 執行Claude Code
claude --verbose --log-level debug

# 檢視日誌檔案
tail -f ~/.claude/logs/claude-debug.log

# 過濾特定錯誤
grep -i "error" ~/.claude/logs/claude-debug.log
grep -i "timeout" ~/.claude/logs/claude-debug.log

技巧3: 错误日志分析

#!/bin/bash
# error-analyzer.sh - 分析Claude Code錯誤日誌

LOG_FILE="$HOME/.claude/logs/latest.log"

echo "=== Claude Code Error Analysis ==="
echo ""

# 統計錯誤型別
echo "1. Error Types:"
grep -i "error" "$LOG_FILE" | awk -F': ' '{print $1}' | sort | uniq -c | sort -rn

echo ""
echo "2. Most Frequent Errors:"
grep -i "error" "$LOG_FILE" | awk -F': ' '{print $NF}' | sort | uniq -c | sort -rn | head -10

echo ""
echo "3. Recent Errors (last 10):"
grep -i "error" "$LOG_FILE" | tail -10

echo ""
echo "4. Warnings:"
grep -i "warning" "$LOG_FILE" | tail -5

echo ""
echo "=== Analysis Complete ==="

技巧4: 创建错误报告模板

当需要报告错误时,使用以下模板:

## Bug Report

### Environment
- Claude Code version: `claude --version`
- Operating system: `uname -a`
- Node.js version: `node --version`
- Network: Corporate/VPN/Home

### Description
[Brief description of the problem]

### Steps to Reproduce
1.
2.
3.

### Expected Behavior
[What should happen]

### Actual Behavior
[What actually happens]

### Error Message

[Paste complete error message including stack trace]


### Logs
```bash
[Paste relevant log output from ~/.claude/logs/]

Configuration

[Paste ~/.claude/config.json, remove sensitive info]

Additional Context

  • When did this start happening?
  • What changed before the error?
  • Is it reproducible?
  • Does it happen in other projects?

### 技巧5: 快速修复清单

```markdown
## Quick Fix Checklist

### Authentication Issues
- [ ] Run `claude auth status`
- [ ] Run `claude auth logout && claude auth login`
- [ ] Check API key is valid
- [ ] Verify account has quota remaining
- [ ] Check for VPN/firewall blocking

### Network Issues
- [ ] Test `ping claude.ai`
- [ ] Test `curl -I https://api.anthropic.com`
- [ ] Check proxy settings
- [ ] Try different network (disable VPN)
- [ ] Flush DNS cache
- [ ] Check firewall rules

### File System Issues
- [ ] Verify file exists: `test -f file.js`
- [ ] Check permissions: `ls -la file.js`
- [ ] Check working directory: `pwd`
- [ ] Use absolute paths
- [ ] Fix ownership: `chown $USER file.js`

### Configuration Issues
- [ ] Validate JSON: `jq '.' ~/.claude/config.json`
- [ ] Reset to defaults: `mv ~/.claude/config.json ~/.claude/config.json.old`
- [ ] Check CLAUDE.md syntax
- [ ] Review recent changes

### API Issues
- [ ] Check rate limits
- [ ] Monitor quota usage: `claude usage`
- [ ] Verify request format
- [ ] Reduce request frequency
- [ ] Wait and retry

常见错误速查表

按错误代码快速查找

错误代码错误类型快速解决方案
AUTH_001Authentication failedclaude auth login
AUTH_002Token expiredclaude auth refresh
NET_001Connection timeoutCheck network, try again
NET_002DNS resolution failedFlush DNS cache
NET_003Connection refusedCheck firewall/proxy
API_001Rate limit exceededWait, then retry
API_002Quota exceededUpgrade plan or wait
API_003Invalid requestCheck request format
FS_001File not foundVerify file path
FS_002Permission deniedchmod u+w file.js
CFG_001Invalid configValidate JSON syntax

按症状快速查找

症状: "无法连接到Claude"

# 檢查清單
1. ping claude.ai
2. curl -I https://api.anthropic.com
3. 檢查VPN連線
4. 檢查代理設定
5. 嘗試關閉防火牆

症状: "认证失败"

# 檢查清單
1. claude auth status
2. claude auth logout && claude auth login
3. 檢查API金鑰
4. 驗證賬戶狀態
5. 確認配額未用盡

症状: "操作很慢"

# 檢查清單
1. 檢查網路速度
2. 清除Claude快取: claude --clear-cache
3. 減少併發操作
4. 分段處理大檔案
5. 考慮升級計劃

症状: "无法修改文件"

# 檢查清單
1. ls -la file.js (檢查許可權)
2. whoami (確認當前使用者)
3. chmod u+w file.js
4. 檢查檔案是否被鎖定
5. 關閉佔用檔案的程式

總結

透過本文的系統介紹,你現在應該能夠:

理解錯誤資訊: 識別錯誤型別、位置和原因

快速定位問題: 使用系統化排查流程

解決常見錯誤: 認證、網路、API、檔案系統、配置錯誤

預防錯誤發生: 建立良好的配置和習慣

有效報告問題: 建立詳細的錯誤報告

關鍵要點

  1. 不要忽視錯誤資訊

    • 完整閱讀錯誤訊息
    • 理解錯誤堆疊
    • 記錄錯誤詳情
  2. 系統化排查

    • 按步驟診斷
    • 隔離問題變數
    • 記錄排查過程
  3. 善用工具

    • 使用除錯模式
    • 分析日誌檔案
    • 利用診斷指令碼
  4. 建立知識庫

    • 記錄常見錯誤
    • 整理解決方案
    • 分享團隊經驗
  5. 預防優於治療

    • 定期維護配置
    • 監控使用情況
    • 及時更新版本

下一步

  • 實踐: 遇到錯誤時應用本文的方法
  • 定製: 為你的專案定製錯誤排查清單
  • 分享: 將新發現的錯誤和解決方案記錄下來
  • 學習: 深入瞭解相關技術(網路、認證、檔案系統)

參考資源


記住:錯誤是正常的,關鍵是要學會如何快速定位和解決問題。掌握錯誤資訊的解讀方法,你就能更從容地應對開發中的各種挑戰,讓Claude Code成為可靠的程式設計助手。