4.4 错误处理与故障恢复
4.4.1 错误的分类与应对策略
import asyncio
class ToolExecutionError(Exception):
"""工具执行错误"""
def __init__(self, tool_name: str, message: str,
error_type: str = None, retry_count: int = 0):
self.tool_name = tool_name
self.message = message
self.error_type = error_type or type(self).__name__
self.retry_count = retry_count
super().__init__(message)
class ToolTimeoutError(ToolExecutionError):
"""工具执行超时"""
pass
class ToolPermissionError(ToolExecutionError):
"""工具权限不足"""
pass
# 处理示例
async def execute_tool_with_recovery(
tool_use: ToolUseBlock,
executor: ToolExecutor,
max_retries: int = 3
) -> ToolResultBlock:
"""执行工具,带重试机制"""
for attempt in range(max_retries):
try:
result = await executor.execute(tool_use.name, tool_use.input)
return ToolResultBlock(
tool_use_id=tool_use.id,
content=str(result),
is_error=False
)
except ToolTimeoutError as e:
# 超时:使用指数退避重试
if attempt < max_retries - 1:
backoff_seconds = 2 ** attempt # 1, 2, 4 秒
await asyncio.sleep(backoff_seconds)
continue
else:
# 最后一次重试失败,返回错误
return ToolResultBlock(
tool_use_id=tool_use.id,
content=f"Tool timeout after {max_retries} retries: {str(e)}",
is_error=True,
error_type="ToolTimeoutError"
)
except ToolPermissionError as e:
# 权限错误:不重试,立即反馈
return ToolResultBlock(
tool_use_id=tool_use.id,
content=f"Permission denied: {str(e)}",
is_error=True,
error_type="ToolPermissionError"
)
except ToolExecutionError as e:
# 其他工具错误:重试一次
if attempt < max_retries - 1:
continue
else:
return ToolResultBlock(
tool_use_id=tool_use.id,
content=f"Tool execution failed: {str(e)}",
is_error=True,
error_type=e.error_type
)
except Exception as e:
# 未预期的异常
return ToolResultBlock(
tool_use_id=tool_use.id,
content=f"Unexpected error: {str(e)}",
is_error=True,
error_type=type(e).__name__
)2. API 调用错误
3. 输出解析错误
4. 上下文溢出与令牌耗尽
4.4.2 OpenClaw 的“错误即观察”模式
4.4.3 断路器模式
4.4.4 本节小结
最后更新于
