🐛 OpenClaw 错误处理与调试完整指南

凌晨3点47分,我的Agent又崩了。错误日志像天书一样,而我像个在代码迷宫里迷路的旅人。如果你也经历过这种绝望,这篇指南就是为你准备的——从错误捕获到调试技巧,让你的Agent从此稳如老狗。

一、OpenClaw 错误类型全解析

在OpenClaw中,错误主要分为以下几类:

1.1 工具执行错误 (Tool Execution Errors)

1.2 Agent 逻辑错误

1.3 系统级错误

二、错误处理最佳实践

2.1 使用 try-catch 模式

在自定义Skills中,始终包裹可能出错的代码:

// SKILL.md 中的错误处理示例
## Error Handling Pattern

When executing shell commands, always handle errors:

```javascript
// Good: 带错误处理
const result = await exec({
  command: "curl -s https://api.example.com/data",
  timeout: 30000
}).catch(err => ({
  success: false,
  error: err.message,
  suggestion: "请检查网络连接或API可用性"
}));

if (!result.success) {
  return `请求失败:${result.error}。建议:${result.suggestion}`;
}
```

2.2 设置合理的超时时间

防止工具调用无限挂起:

# 推荐超时配置
{
  "web_fetch": { "timeoutMs": 15000 },
  "web_search": { "timeoutMs": 10000 },
  "exec": { "timeout": 30 },
  "browser": { "timeoutMs": 20000 }
}

2.3 实现重试机制

对于网络请求,实现指数退避重试:

// 重试逻辑示例
async function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const result = await web_fetch({ url });
      return result;
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      await sleep(Math.pow(2, i) * 1000); // 1s, 2s, 4s
    }
  }
}
💡 关键原则:永远不要让Agent在错误面前"卡住",提供清晰的错误信息和可行的替代方案。

三、调试技巧与工具

3.1 启用详细日志

在 Gateway 配置中开启调试模式:

# config.yaml
logging:
  level: debug
  tools: true        # 记录工具调用
  llm_calls: true    # 记录LLM请求
  sessions: true     # 记录会话状态变化

3.2 使用 sessions_history 追踪问题

当Agent行为异常时,查看历史记录:

# 获取最近100条消息
sessions_history({
  sessionKey: "problematic-session",
  limit: 100,
  includeTools: true
})

3.3 分步调试法

  1. 隔离问题:将复杂任务拆分为单步测试
  2. 验证输入:检查每个工具调用的参数
  3. 验证输出:确认工具返回格式正确
  4. 检查状态:查看session状态是否一致

3.4 使用 subagent 进行沙盒测试

在隔离环境中测试可疑代码:

sessions_spawn({
  task: "测试这个可疑的功能",
  runtime: "subagent",
  mode: "run",
  timeoutSeconds: 60
})

四、常见错误及解决方案

4.1 "Tool not found" 错误

原因:Skill未正确加载或工具名称拼写错误
解决:检查 SKILL.md 位置、验证工具名称、重启 Gateway

4.2 "Context window exceeded" 错误

原因:会话历史过长,超出模型上下文限制
解决:定期清理历史、使用 summarization、开启上下文压缩

4.3 "Rate limit exceeded" 错误

原因:API调用过于频繁
解决:实现请求队列、添加延迟、使用本地缓存

4.4 工具调用循环

原因:Agent陷入工具调用死循环
解决:设置最大调用次数、使用 yield 中断、添加循环检测逻辑

五、高级调试模式

5.1 交互式调试

使用 process 工具管理后台会话:

// 启动交互式调试会话
exec({
  command: "openclaw debug --session my-session",
  pty: true
})

5.2 性能分析

监控Agent性能瓶颈:

# 查看工具调用耗时统计
session_status({ sessionKey: "my-session" })

六、监控与告警

建立完善的监控体系:

🎯 总结:调试Agent就像侦探破案——收集证据、分析线索、验证假设。掌握了这些技巧,你就能从容应对各种"凌晨3点的崩溃"。