第五部分:故障排查
本节目的:快速解决Hook配置和执行问题
⏱️ 预计时间:按需查阅
5.1 Hook不执行
症状:配置了Hook但完全没有触发
排查步骤:
- 检查配置文件路径
bash
# 确认settings.json在正确位置
ls -la .claude/settings.json
# 应该存在且有内容- 检查JSON格式
bash
# 验证JSON格式
python -c "import json; json.load(open('.claude/settings.json'))"
# 没有报错说明格式正确- 检查Matcher是否匹配
json
// 错误:matcher拼写错误
"matcher": "write" // X 应该是大写W
// 正确
"matcher": "Write" // V- 检查脚本路径
bash
# 确认脚本存在
ls -la .claude/hooks/your-hook.py
# macOS/Linux检查执行权限
chmod +x .claude/hooks/your-hook.py- 重启Claude Code
bash
# 退出当前会话
exit
# 重新启动
claude5.2 Hook执行报错
症状:Hook触发了但报错退出
排查步骤:
- 手动测试脚本
bash
# 模拟输入测试
echo '{"tool_name": "Write", "tool_input": {"file_path": "test.txt"}}' | python .claude/hooks/your-hook.py
# 查看输出和错误- 检查Python版本
bash
python --version
# 应该是Python 3.x- 检查依赖是否安装
bash
# 如果脚本import了第三方库
pip install 缺少的库- 查看stderr输出
python
# 在脚本中添加调试输出
import sys
print("DEBUG: 脚本开始执行", file=sys.stderr)
print(f"DEBUG: 收到输入: {input_data}", file=sys.stderr)5.3 Hook超时
症状:Hook执行时间过长被强制终止
解决方案:
- 增加timeout配置
json
{
"type": "command",
"command": "python .claude/hooks/slow-hook.py",
"timeout": 120 // 增加到120秒
}- 优化脚本性能
python
# 避免不必要的文件扫描
# 使用增量检查而不是全量检查
# 并行执行多个检查任务- 异步处理
python
# 对于不需要阻塞的任务,可以后台执行
import subprocess
subprocess.Popen(['python', 'background-task.py'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)5.4 Windows特有问题
问题1:中文乱码
症状:Hook输出中文显示为乱码
解决方案:
python
# 在脚本开头设置编码
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')问题2:路径分隔符
症状:Windows路径包含反斜杠导致问题
解决方案:
python
# 统一处理路径
file_path = file_path.replace('\\', '/')问题3:Batch脚本编码
症状:.bat文件中文乱码
解决方案:
batch
@echo off
chcp 65001 >nul
REM 脚本内容...5.5 调试技巧
技巧1:日志文件
python
# 写入调试日志
from pathlib import Path
from datetime import datetime
log_file = Path.home() / '.claude' / 'hooks-debug.log'
log_file.parent.mkdir(parents=True, exist_ok=True)
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"[{datetime.now()}] {message}\n")技巧2:条件调试
python
import os
# 通过环境变量控制调试模式
DEBUG = os.getenv('CLAUDE_HOOK_DEBUG', '').lower() == 'true'
if DEBUG:
print(f"DEBUG: {data}", file=sys.stderr)技巧3:逐步排除法
json
// 先只保留一个Hook测试
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "echo 'Hook triggered!' >&2"
}
]
}
]
}
}