Error Handling in Tools
Comprehensive error handling strategies for tools including retries, timeouts, and validation
Tools can fail for many reasons, network issues, timeouts, invalid API responses, or broken external services. Peargent provides a complete system to handle these failures gracefully.
Error Handling with on_error
The on_error parameter controls how tools handle errors (execution failures or validation failures):
from peargent import create_tool
# Option 1: Raise exception (default)
tool_strict = create_tool(
name="critical_api",
description="Critical API call that must succeed",
input_parameters={"query": str},
call_function=call_api,
on_error="raise" # Fail fast if error occurs
)
# Option 2: Return error message as string
tool_graceful = create_tool(
name="optional_api",
description="Optional API call",
input_parameters={"query": str},
call_function=call_api,
on_error="return_error" # Continue with error message
)
# Option 3: Return None silently
tool_silent = create_tool(
name="analytics_tracker",
description="Optional analytics tracking",
input_parameters={"event": str},
call_function=track_event,
on_error="return_none" # Ignore failures silently
)When to Use Each Strategy
on_error Value | What Happens | What You Can Do | Use Case | Example |
|---|---|---|---|---|
"raise" (default) | Raises exception, stops agent execution | Wrap in try/except to catch and handle exception | Critical tools that must succeed | Database writes, payment processing |
"return_error" | Returns error message as string (e.g., "Tool 'api_call' failed: ConnectionError: ...") | Check if result is string and contains error, then handle gracefully | Graceful degradation, logging errors | Optional external APIs, analytics |
"return_none" | Returns None silently, no error message | Check if result is None, then use fallback value or skip | Non-critical features, optional enrichment | Analytics tracking, optional data enrichment |
Next: Advanced Error Handling
Peargent provides more robust failure-handling features:
-
Retries
Automatically retry failing tools with optional exponential backoff. -
Timeouts
Prevent long-running or hanging operations. -
Validation Failures
Handle schema validation errors when usingoutput_schema.
These pages go deeper into reliability patterns for production workloads.