AI AgentsLangChain
How do you handle tool exceptions and recoverable errors?
Question 297 of 324 · Updated
On this page
- Direct answer
- 1. Understand where a tool failure occurs
- 2. Use ToolException for anticipated tool failures
- What handle_tool_error controls
- 3. Treat validation failures separately
- 4. Convert an expected failure into a correlated ToolMessage
- 5. Error classification and recovery policy
- 6. Bounded retries versus model corrections
- 7. Tested Python implementation: a safe tool failure boundary
- 8. Preserve protocol and state during failures
- 9. Observability without leaking sensitive data
- 10. Production failure testing
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In LangChain, classify a tool failure before deciding whether to convert it into an error observation or let the exception propagate. Use ToolException for expected tool-level failures, configure handle_tool_error to return a safe message where appropriate, and handle argument-validation failures separately through supported validation-error settings. In an agent, a wrap_tool_call middleware can translate selected domain exceptions into a correlated ToolMessage. Unknown programming failures, security-policy violations that require termination, cancellation and framework control-flow signals must not be blindly swallowed.
A recoverable error means that some safe next step is available; it does not necessarily mean the same operation should be retried. A model may need to correct arguments, ask the user for missing information, or stop with a truthful explanation. For an uncertain write, reconcile the external outcome before any replay.
This lesson follows the tool argument-validation and structured-content lessons (#293 and #296). AI Agents #40, #89 and #90 already explain generic failure recovery and bounded retries, and #155 explains idempotent workflow steps. The distinct objective here is LangChain's exception-handling interfaces, error-message correlation, the distinction between recoverable observations and execution termination, and concrete application tests. Detailed retry and fallback middleware configuration is reserved for the later dedicated lesson.
1. Understand where a tool failure occurs#
A tool request passes through several distinct boundaries. A failure during argument parsing is not the same as a timeout after the service has accepted an action.
| Boundary | Example failure | Appropriate responsibility |
|---|---|---|
| Tool dispatch | Unknown tool name | Runtime rejects or reports unsupported capability |
| Argument parsing and validation | Invalid ID or missing required field | Local schema validator rejects request |
| Authorization | Resource belongs to another tenant | Trusted domain service denies access |
| Domain execution | Record cannot currently be read | Tool or service classifies expected failure |
| External commitment | Write timed out after submission | Domain service reconciles authoritative outcome |
| Result validation | Invalid response shape or mismatched evidence | Application rejects unsupported observation |
| Framework or application execution | Unexpected exception or cancellation | Host handles failure or control flow |
The error boundary should preserve the distinction between an expected business outcome and an infrastructure or implementation fault. For example, a read-only lookup may legitimately find no visible record. It can return a normal result such as {"status":"unavailable"} when absence is part of its contract. That is different from an unexpected exception that prevents the tool from knowing the result.
Do not report an unsuccessful action as an empty successful result merely to keep the model loop running.
This is the recommended application-level decision flow, not a guarantee that a specific LangChain release automatically implements every classification.
2. Use ToolException for anticipated tool failures#
Modern LangChain tool abstractions expose ToolException, an exception type for tool-execution failures that the application may choose to handle as observations rather than terminate the run. In common BaseTool implementations, the handle_tool_error setting determines whether and how a ToolException is converted into a result.
The setting does not catch arbitrary exceptions. A ValueError, RuntimeError, network exception or Pydantic ValidationError is not automatically a ToolException. Catch and translate only the specific expected exceptions for which the application has a reviewed recovery policy.
The following illustrative SDK example uses StructuredTool.from_function to register an expected fictional lookup failure and a safe error formatter.
PYTHONfrom langchain_core.tools import StructuredTool, ToolException def read_demo_record(record_id: str) -> str: """Read the status of a synthetic record by exact ID.""" if record_id != "R-1": raise ToolException("demo_record_unavailable") return "open" def safe_tool_error(exc: ToolException) -> str: # Return a reviewed message, not arbitrary exception text. return "Record unavailable. Check the identifier or stop." read_record = StructuredTool.from_function( func=read_demo_record, name="read_record", handle_tool_error=safe_tool_error, ) print(read_record.invoke({"record_id": "R-1"})) print(read_record.invoke({"record_id": "R-2"}))
The intended successful result is open and the intended handled error is the reviewed unavailable message. These are illustrative expectations rather than executed LangChain output. The example accesses only synthetic records. A real record lookup must check authenticated resource permissions, and must not disclose the existence of inaccessible records.
Verification note: LangChain, langchain_core and langgraph were absent from the local Python environment. Framework examples in this lesson are illustrative and unexecuted. Exact option support, signatures and tool-message behavior must be verified in the installed release. The standalone application recovery policy in section 7 was actually executed on Python 3.13.5 with Pydantic 2.13.5.
What handle_tool_error controls#
In common modern BaseTool implementations, the option accepts a Boolean, string or callback. Confirm the exact type and default against the installed release.
| Setting | Intended behavior | Caveat |
|---|---|---|
| False | Do not handle ToolException at this tool-level boundary | A surrounding tool node or middleware may still handle it |
| True | Use the exception's message or a framework fallback | Raw exception text may disclose sensitive data |
| Fixed string | Return reviewed static guidance | May be too generic for multiple failure classes |
| Callable | Convert the ToolException into approved guidance | Formatter must not reveal raw exception details |
Prefer a reviewed fixed string or a controlled formatter over returning str(exc) indiscriminately. An exception may contain upstream response bodies, SQL fragments, private identifiers, credential-bearing URLs or text supplied by an untrusted external service.
A formatter itself should be deterministic and small. Do not make an unbounded network call inside it. Avoid throwing new unexpected exceptions while attempting to report the original failure.
3. Treat validation failures separately#
Input-validation errors occur before the domain operation is allowed to execute. They should not be treated as transient outages. The corrective action is to obtain a valid input, not to repeat the same malformed payload.
A compatible LangChain tool can expose a separate handle_validation_error setting for Pydantic argument-validation failures. The following SDK illustration reuses read_demo_record from the previous section and defines a narrow public argument schema.
PYTHONfrom pydantic import BaseModel, ConfigDict, Field from langchain_core.tools import StructuredTool class RecordArgs(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") record_id: str = Field(pattern=r"^R-[0-9]+$") validated_read = StructuredTool.from_function( func=read_demo_record, name="validated_read", args_schema=RecordArgs, handle_tool_error="Record unavailable.", handle_validation_error="Provide a valid record_id, such as R-1.", )
The intended behavior is that malformed arguments receive safe correction guidance without executing read_demo_record. This SDK snippet was not executed. Check the actual installed tool runtime because schema errors may also arise during provider parsing, tool dispatch or validation performed outside the tool's own input-validation path.
A Pydantic ValidationError raised inside a domain service may represent an invalid upstream result rather than invalid model input. Do not automatically tell the user to correct their input when the real problem is a broken upstream response. Preserve the validation boundary in the error classification.
The earlier #293 lesson explains strict types, nested schemas and field constraints in detail. Here the focus is the distinction between input rejection, tool-level expected failure and host-level fault propagation.
4. Convert an expected failure into a correlated ToolMessage#
When a model proposes a tool call, its call identifier links the request with the corresponding tool observation. In a supported agent execution path, a handled ToolException may be represented as a ToolMessage, including an error status where the installed message and adapter support it.
A custom agent middleware can also translate selected domain exceptions into a sanitized tool observation. The following illustration uses the wrap_tool_call decorator; it is an alternative boundary to the tool-level handling in section 2, not a requirement to stack both handlers.
PYTHONfrom langchain.agents import create_agent from langchain.agents.middleware import wrap_tool_call from langchain_core.messages import ToolMessage from langchain.tools import tool class ReadUnavailable(Exception): pass @tool def read_status(record_id: str) -> str: """Read a synthetic status without changing any record.""" if record_id != "R-1": raise ReadUnavailable("internal synthetic service detail") return "open" @wrap_tool_call def expected_read_error(request, handler): try: return handler(request) except ReadUnavailable: return ToolMessage( content=( '{"code":"unavailable",' '"message":"Status could not be verified."}' ), tool_call_id=request.tool_call["id"], status="error", ) agent = create_agent( model="openai:gpt-4o-mini", tools=[read_status], middleware=[expected_read_error], system_prompt=( "Use verified status observations. " "Do not invent a status when a lookup fails." ), )
This example does not execute a live provider call. Verify the installed middleware API, the request's tool-call representation and ToolMessage status support before use. The model ID is illustrative. Depending on the tool-node configuration, an inner execution layer may already convert some exceptions to messages; a surrounding middleware can catch an exception only if it actually propagates to that handler. Test the real execution path and avoid double wrapping an already correlated observation.
The callback catches only ReadUnavailable. It does not treat every exception as a recoverable error, and it does not expose the exception's internal string. The model receives an explicit indication that the status could not be verified.
The error status is useful runtime metadata, but its provider-facing representation varies. Make the content itself unambiguously describe failure. Do not depend on an application-only metadata flag being visible to the model.
The diagram distinguishes a model continuation from exception propagation. If execution terminates, the runtime may not send a new request to the model. Avoid fabricating a successful ToolMessage merely to complete the message sequence.
5. Error classification and recovery policy#
A recoverable error is relative to the current operation, workload and available budget. The same timeout may be safely retried for a read, yet require reconciliation for a write.
| Failure class | Example | Safe handling |
|---|---|---|
| Correctable input | Invalid record ID | Reject before execution; request a corrected argument |
| Missing prerequisite | Required user selection absent | Ask for clarification or route to approval |
| Expected business rejection | Unsupported service option | Return bounded failure guidance |
| Permission denied | Resource outside the caller's scope | Deny; do not try another identity |
| Transient read failure | Temporary read service unavailable | Retry only under a bounded safe policy |
| Rate limit | Provider requests reduced request rate | Respect service policy and remaining deadline |
| Uncertain mutation | Write acknowledgement lost | Reconcile; no blind replay |
| Invalid result | Upstream returns inconsistent record | Reject unsupported evidence; investigate |
| Programming fault | Unexpected invariant violation | Propagate and alert appropriately |
| Cancellation or interrupt | Host cancels or graph pauses | Preserve framework and host control semantics |
For an expected unavailable result, a model-facing error object can contain a stable code, short reviewed message and guidance. A retryability flag is advisory only; execution limits and authorization must be enforced by the host. Never let the model override a denied operation because an error message describes a possible workaround.
Do not catch BaseException to keep the conversation alive. KeyboardInterrupt, SystemExit, cancellation and framework-specific control-flow signals have special semantics. Some framework interrupt exceptions are derived from ordinary Exception, so even a broad except Exception may be unsafe in a middleware. Prefer specific exception classes and re-raise unrecognized failures.
In an async tool, preserve cancellation. Use the async middleware and handler interface supported by the installed runtime. A canceled wait does not prove the remote operation was canceled or rolled back. If a state-changing request was already submitted, the domain service must establish the final outcome independently.
6. Bounded retries versus model corrections#
There are at least two recovery loops:
- The application may internally retry a safe transient operation without making another model call.
- The model may receive a correction observation and propose a new call with revised arguments.
Both consume resources. A tool-level cap alone does not prevent the agent from repeatedly requesting the same failing tool. An agent-level cap alone does not prevent an SDK or HTTP client from performing several internal retries for every tool request.
For example, suppose a workflow permits four model-generated calls to a read tool, and the tool client permits three total service attempts per call. The worst-case number of service attempts is twelve before other layers' retries. If a lower-level transport independently makes two attempts per service attempt, the theoretical total becomes twenty-four. These are arithmetic illustrations, not observed measurements. Track the effective retry budget across all layers.
For safe transient reads, use a small approved attempt limit, deadline, timeout and appropriate backoff with jitter. Respect provider rate-limit information when available. Stop when the remaining budget is insufficient. For invalid inputs, require a meaningful correction before trying again. For policy denials, stop that operation.
For writes, the default must be conservative: a timeout may mean that the server applied the mutation but the response was lost. Do not generate a new payment, message, booking or business operation merely because the previous response was missing.
A reliable idempotency design binds a stable logical operation ID to the authenticated caller and approved payload, and enforces deduplication atomically at the authoritative service. Reuse the same key only for the same authorized logical operation. A tool-call ID is a correlation identifier, not automatically a durable business idempotency key.
The detailed middleware retry and fallback lesson later in this sequence covers framework-specific retry configurations. Here the goal is to decide whether a failure is eligible for recovery at all.
7. Tested Python implementation: a safe tool failure boundary#
The following standalone implementation uses actual Pydantic v2 input validation and a scripted domain service. It deliberately does not depend on LangChain. It tests error classification, sanitized responses, bounded read attempts, conservative handling of uncertain writes and propagation of unexpected failures.
PYTHONfrom dataclasses import dataclass from pydantic import BaseModel, ConfigDict, Field, ValidationError class Args(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') record_id: str = Field(pattern=r'^R-[0-9]+$') class Denied(Exception): pass class Transient(Exception): pass class UnknownCommit(Exception): pass @dataclass(frozen=True) class Outcome: code: str detail: str attempts: int def execute(raw, service, *, read_only, max_attempts=2): if type(max_attempts) is not int or not 1 <= max_attempts <= 3: raise ValueError('invalid retry budget') try: args = Args.model_validate(raw) except ValidationError: return Outcome('invalid_input', 'Provide a valid record ID.', 0) for attempt in range(1, max_attempts + 1): try: result = service(args.record_id) except Denied: return Outcome('denied', 'Record unavailable.', attempt) except UnknownCommit: return Outcome('uncertain', 'Outcome not verified; reconcile first.', attempt) except Transient: if not read_only: return Outcome('uncertain', 'Outcome not verified; reconcile first.', attempt) if attempt == max_attempts: return Outcome('unavailable', 'Service temporarily unavailable.', attempt) else: if result not in ('open', 'closed'): raise RuntimeError('unexpected domain result') return Outcome('ok', result, attempt) class Script: def __init__(self, *steps): self.steps = iter(steps) self.calls = [] def __call__(self, record_id): self.calls.append(record_id) step = next(self.steps) if isinstance(step, Exception): raise step return step p = {'record_id':'R-1'} s = Script('open') assert execute(p, s, read_only=True) == Outcome('ok','open',1) s = Script('open') assert execute({'record_id':1}, s, read_only=True).code == 'invalid_input' and not s.calls assert execute({**p,'tenant':'b'}, s, read_only=True).code == 'invalid_input' and not s.calls s = Script(Transient('SECRET'), 'closed') assert execute(p,s,read_only=True) == Outcome('ok','closed',2) and len(s.calls)==2 s = Script(Transient('SECRET'), Transient('SECRET')) assert execute(p,s,read_only=True) == Outcome('unavailable','Service temporarily unavailable.',2) s = Script(Denied('SECRET')) assert execute(p,s,read_only=True) == Outcome('denied','Record unavailable.',1) s = Script(UnknownCommit('SECRET')) assert execute(p,s,read_only=False).code == 'uncertain' and len(s.calls)==1 s = Script(Transient('SECRET')) assert execute(p,s,read_only=False).code == 'uncertain' and len(s.calls)==1 for step in (RuntimeError('bug'), 'invalid'): s = Script(step) try: execute(p,s,read_only=True) except RuntimeError: pass else: raise AssertionError('unexpected fault suppressed') assert len(s.calls)==1 try: execute(p, Script('open'), read_only=True, max_attempts=0) except ValueError: pass else: raise AssertionError('invalid retry budget accepted') print('11 scenarios passed')
Actual local execution on Python 3.13.5 with Pydantic 2.13.5 printed:
11 scenarios passed| Scenario | Verified behavior |
|---|---|
| Successful lookup | Verified open status |
| Invalid identifier type | Rejected before service invocation |
| Unexpected tenant argument | Rejected before service invocation |
| Transient read failure then success | Succeeds in two attempts |
| Repeated transient read failure | Stops at the configured cap |
| Permission denied | Safe unavailable message; no retry |
| Unknown write commitment | Returns uncertain; exactly one call |
| Transient error on write | Returns uncertain; exactly one call |
| Programming exception | Propagates instead of being disguised |
| Unexpected result | Raises an application invariant error |
| Invalid retry budget | Rejected before invocation |
The synthetic SECRET marker appears in exception fixtures, not in the asserted sanitized denial or unavailable messages. The write tests verify absence of automatic replay, not actual idempotency enforcement or reconciliation. The service's authenticated scope and whether an operation is genuinely read-only must be established by trusted host code; they must not be supplied by the model. This small policy does not implement authentication, timeouts, backoff, concurrent execution, external commits, durable operation records or the LangChain middleware itself. Immediate retries are intentional for deterministic local tests; production network calls require an appropriate deadline and delay policy.
In a real integration, map the approved Outcome values to the tool's documented response contract. An invalid_input outcome can guide a bounded correction; denied must not trigger attempts with alternate tenants; uncertain must never be translated into success. Unknown errors should reach the host execution boundary where the application can record redacted diagnostics and return an honest failure status.
8. Preserve protocol and state during failures#
An error observation belongs to the particular tool call that failed. In a batch of parallel calls, do not attach one tool's error to another tool's ID or discard all successful observations simply because one lookup failed. The runtime must follow the provider's supported message sequencing and correlate each accepted result.
If a tool performs several external operations and fails midway, a single generic error is often insufficient. Persist enough trusted evidence to determine which operations committed, which failed and which remain uncertain. Do not report a batch as wholly successful without verification.
When an agent stops because of an exception, the last checkpoint may reflect only a previous successful graph boundary. An external mutation may have committed after that checkpoint. Recovery must consult authoritative domain state, not assume graph replay will roll back side effects.
Do not confuse an expected business denial with a missing context or unavailable credentials. A missing authenticated runtime context is a host configuration or lifecycle error. The model must not be invited to invent the missing identity or supply a credential as a replacement.
9. Observability without leaking sensitive data#
Useful telemetry distinguishes proposals, attempts, tool outcomes and complete agent outcomes. Record stable classifications rather than raw exception strings.
| Safe operational field | Purpose |
|---|---|
| Tool identifier and version | Identify the failing implementation |
| Error category | Group malformed input, denial, timeout, uncertain write and fault |
| Correlation alias | Associate a result with an authorized run |
| Attempt count and elapsed time | Identify budget exhaustion and retry amplification |
| Recovery decision | Correction, retry, stop, propagate or reconcile |
| Commit status | Distinguish known result from unknown external effect |
| Final task status | Determine whether the user goal was actually achieved |
Use protected diagnostics for stack traces only when policy permits; redact sensitive input and restrict access and retention. Avoid logging whole tool request objects, raw context, credentials, private resource identifiers or upstream response bodies by default.
Measure error rates by failure class rather than treating all tool failures as the same problem. A spike in validation failures can indicate ambiguous tool metadata or schema incompatibility. A spike in permission denials can indicate incorrect policy routing or attack attempts. A spike in uncertain writes requires immediate attention to the authoritative service and reconciliation controls. A retry-success rate alone is not a safety metric.
10. Production failure testing#
Use deterministic unit tests for the application's recovery policy, then verify the actual SDK execution graph, tool-node configuration and selected provider adapter. Live tests should be separately approved and use synthetic data or a controlled test environment.
| Failure injection | Required acceptance condition |
|---|---|
| Missing argument or wrong type | Domain operation never executes |
| Explicit ToolException | Configured safe formatter produces expected error behavior |
| Unhandled ToolException | Observed propagation or documented surrounding handler behavior |
| Unexpected exception | Not silently transformed into a successful observation |
| Expected middleware exception | Correct ToolMessage correlation and sanitized error content |
| Already handled error | No duplicate tool message or second execution |
| Malformed upstream response | No unsupported factual claim |
| Permission failure | No alternative-identity retry or sensitive existence disclosure |
| Transient read | Correct attempt budget and deadline behavior |
| Write timeout after possible commit | No automatic duplicate mutation |
| Cancellation or graph interrupt | Control flow is preserved |
| Parallel tool calls | Independent results and errors remain correctly correlated |
| Failure during recovery | Stop within bounded policy and preserve evidence |
Test the model's behavior after receiving an error observation as well. The application should reject claims such as "the operation succeeded" when the only tool result was unavailable or uncertain. It should not depend solely on the model following a textual retry instruction.
Pin framework and provider integration versions, document the effective error-handling stack and confirm which layer owns each decision. Check how tool-level handlers, middleware, tool nodes, transport retries and graph recovery interact. Prevent retry amplification and inconsistent error messages across layers.
Interview-ready answer#
I separate LangChain tool failures by execution boundary and recovery policy. For expected tool-level exceptions I can raise ToolException and configure handle_tool_error to emit reviewed guidance. Input-validation failures use a separate validation handler where supported. I can use wrap_tool_call middleware to translate a specific domain exception into a sanitized ToolMessage correlated with the original tool call. I retry only safe transient operations within explicit budgets, reject invalid or unauthorized requests, reconcile uncertain writes before replay, and allow unexpected faults and control-flow signals to propagate appropriately. I test the actual SDK behavior separately from the deterministic application policy and never let an error handler falsely claim that a task succeeded.
Official documentation research leads and verification status#
- LangChain tools
- LangChain middleware overview
- LangChain middleware custom implementations
- LangChain messages
- LangChain API reference
- LangGraph persistence
- Pydantic validation errors
- Python exceptions
Authorized offline research exception applied. The official documentation URLs are research leads, not live-accessed citations. Python 3.13.5 and Pydantic 2.13.5 were available locally; the standalone recovery implementation was actually executed and all 11 scenarios passed. LangChain, langchain_core and langgraph were absent, so SDK examples, middleware behavior, ToolException and ToolMessage integration, current signatures and provider conversion were not executed or live-verified. The diagrams use standard triple-backtick Mermaid fences; rendering and public website display were not verified. No live external operations or credentials were used.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain middleware overviewdocs.langchain.com
- 3.LangChain middleware custom implementationsdocs.langchain.com
- 4.LangChain messagesdocs.langchain.com
- 5.LangChain API referencereference.langchain.com
- 6.LangGraph persistencedocs.langchain.com
- 7.Pydantic validation errorsdocs.pydantic.dev
- 8.Python exceptionsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps