"""14: Error handling: max_turns and max_budget_usd limits, ResultError, bad CLI path."""
import asyncio
from claude_agent_sdk import (
ClaudeAgentOptions,
CLINotFoundError,
ProcessError,
ResultError,
ResultMessage,
query,
)
from demo_util import PROJECT
async def run(label, **opts):
print(f"\n=== {label} ===")
try:
async for message in query(
prompt="List every file in this project, read each one, then summarize the project.",
options=ClaudeAgentOptions(cwd=PROJECT, allowed_tools=["Read", "Glob"], **opts),
):
if isinstance(message, ResultMessage):
print(f"ResultMessage: subtype={message.subtype} is_error={message.is_error} "
f"turns={message.num_turns} cost=${message.total_cost_usd or 0:.4f} "
f"terminal_reason={message.terminal_reason!r}")
print(f" result field: {message.result!r}")
except CLINotFoundError as e:
print(f"CLINotFoundError: {e}")
except ResultError as e: # subclass of ProcessError: catch it first
print(f"ResultError raised after the result: subtype={e.subtype} terminal_reason={e.terminal_reason!r}")
print(f" message: {e}")
except ProcessError as e:
print(f"ProcessError: exit_code={e.exit_code}")
async def main():
await run("max_turns=1", max_turns=1)
await run("max_budget_usd=0.02", max_budget_usd=0.02)
await run("bad cli_path", cli_path="/nonexistent/claude", max_turns=1)
asyncio.run(main())
44 lines · Back to the folder