🛡️ OpenClaw错误处理策略教程

让Agent稳如老狗的容错秘籍——毕竟,再聪明的AI也会翻车

📖 功能介绍

凌晨3点47分,Agent突然返回了一个"Unknown Error"。我盯着屏幕,想起了前任说过的话:"没有错误处理的代码,就像没有安全措施的爱情——早晚会出事。"

OpenClaw的错误处理系统提供了多层防护机制:从简单的重试到复杂的熔断器,从优雅降级到故障转移。这不是为了消灭错误,而是让错误变得可预测、可恢复、可原谅。

错误类型分类

错误类型 典型原因 处理策略
瞬态错误 网络超时、API限流 指数退避重试
持久错误 参数错误、权限不足 快速失败+告警
资源耗尽 内存溢出、并发超限 降级+排队
依赖故障 下游服务不可用 熔断+降级

🚀 使用方法

1. 基础重试机制

最简单也最有效的策略。Agent失败了?让它再试一次。但不是傻傻地试——要讲究策略。

🔄 指数退避重试配置

error_handling:
  retry:
    enabled: true
    max_attempts: 3
    strategy: "exponential_backoff"
    
    # 初始等待时间
    initial_delay: 1s
    
    # 最大等待时间
    max_delay: 30s
    
    # 退避倍数
    multiplier: 2
    
    # 添加抖动防止惊群效应
    jitter: true
    jitter_range: "0.5-1.5"
    
    # 可重试的错误类型
    retry_on:
      - "timeout"
      - "rate_limit"
      - "temporary_unavailable"
      - "connection_refused"

2. 熔断器模式

当错误率达到阈值时,主动"断电"防止雪崩。就像家里的保险丝,短路了先跳闸,别把整个房子烧了。

[关闭状态] → 错误率超阈值 → [打开状态] → 冷却时间 → [半开状态] → 测试请求
↑ │
└──────────────────── 测试成功 ←─────────────────────────┘
circuit_breaker:
  enabled: true
  
  # 触发熔断的条件
  failure_threshold: 5        # 连续失败次数
  failure_rate_threshold: 0.5 # 失败率阈值
  
  # 时间窗口
  evaluation_window: 60s
  
  # 熔断持续时间
  open_duration: 30s
  
  # 半开状态测试
  half_open:
    test_requests: 3
    success_threshold: 2

3. 降级策略

主路不通走辅路。API挂了?用缓存。模型超时?换个简单的模型。总比直接给用户报错强。

fallback:
  enabled: true
  strategies:
    # 降级方案1:使用缓存
    - type: "cache"
      ttl: 3600
      
    # 降级方案2:切换模型
    - type: "model_switch"
      fallback_model: "gpt-4o-mini"
      
    # 降级方案3:返回默认回复
    - type: "static_response"
      template: "服务暂时繁忙,请稍后重试"
      
    # 降级方案4:队列延迟处理
    - type: "queue"
      queue_name: "pending_tasks"
      notify: true

💡 最佳实践

🎯 错误处理设计原则:
  • 快速失败:无法恢复的错误立即返回,别浪费时间重试
  • 优雅降级:总能给用户点什么,哪怕是道歉
  • 可观测性:每个错误都要有日志和监控
  • 幂等设计:重试不会产生副作用

错误处理决策树

错误发生
  ├── 是瞬态错误吗?
  │   ├── 是 → 指数退避重试(最多3次)
  │   └── 否 → 是持久错误吗?
  │              ├── 是 → 快速失败 + 记录日志
  │              └── 否 → 资源问题?
  │                        ├── 是 → 降级处理
  │                        └── 否 → 熔断器判断
  │                                  ├── 熔断器打开 → 返回降级响应
  │                                  └── 熔断器关闭 → 正常重试
⚠️ 避坑指南:
  • 重试次数不是越多越好,3次足够了,再多就是浪费
  • 不要对所有错误都重试,持久错误重试只会浪费钱
  • 熔断器的阈值要根据实际QPS调整,别太敏感也别太迟钝
  • 降级方案要有,但别太复杂,否则降级本身也是故障点

🔧 完整配置示例

# OpenClaw 完整错误处理配置
agent:
  name: "resilient_agent"
  
  error_handling:
    # 全局配置
    timeout: 120s
    max_retries: 3
    
    # 重试策略
    retry:
      strategy: "exponential_backoff"
      initial_delay: 1s
      max_delay: 30s
      jitter: true
      
    # 熔断器
    circuit_breaker:
      enabled: true
      failure_threshold: 5
      open_duration: 30s
      
    # 降级策略(按优先级)
    fallback:
      - type: "cache_fallback"
        ttl: 3600
      - type: "model_switch"
        model: "claude-sonnet-4"
      - type: "static_response"
        message: "服务暂时不可用,已记录您的请求"
        
    # 错误通知
    alerting:
      enabled: true
      channels:
        - type: "feishu"
          webhook: "${ALERT_WEBHOOK}"
      severity_levels:
        - level: "warning"
          threshold: 3  # 连续3次失败告警
        - level: "critical"  
          threshold: 10 # 连续10次失败紧急告警
          
    # 错误日志
    logging:
      enabled: true
      level: "error"
      include_context: true
      include_stack_trace: false

🔗 相关链接