---
title: "Handling Tool Errors and Raising Recoverable Exceptions to the LLM"
date: "2026-11-27T08:30:00+07:00"
description: "What the model actually sees when a tool fails, how to distinguish recoverable from terminal errors, writing error messages that produce a correct retry, sanitising output, and partial success patterns."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-tool-errors-recoverable-exceptions.jpg"
alt: "Wrench handing a repair slip to a robot at a workbench"
tags: ['google-adk', 'error-handling', 'function-tools', 'reliability', 'observability']
---

A tool failure is not the end of a turn — it is information handed back to the model, which will decide what to do with it. Hand it a stack trace and the model improvises; hand it a precise, repairable description and the model does the thing you wanted: correct the call, choose another tool, or tell the user plainly.

This tutorial covers the mechanics (what the framework puts in front of the model when your function raises or returns an error), how to classify failures, and the message-writing discipline that turns errors into recoveries.

## What the model sees

Two paths, both visible to the model:

**1. You return an error dict.** The tool completes normally, and your payload becomes the function response:

```python
def get_invoice(invoice_id: str) -> dict:
    """Fetch an invoice by ID.

    Args:
        invoice_id (str): Invoice identifier, e.g. 'INV-4821'.
    """
    invoice = store.get(invoice_id)
    if invoice is None:
        return {'status': 'error', 'error_message': f'No invoice {invoice_id} exists.'}
    return {'status': 'success', 'invoice': invoice}
```

**2. You raise.** The framework catches it and puts an error result into the conversation so the model can react. The Gen AI SDK documents the same pattern explicitly: *instead of raising the exception, you can let the model handle it* — wrapping the exception text as `{'error': str(e)}`.

Which to choose? **Return a dict for expected, domain-level failures** (not found, permission denied, already processed). **Raise for programming errors** (bug, misconfiguration) that should surface to your error monitoring rather than into the conversation.

Either way, the model now holds an error and will act on it — which makes the *content* of that error a design surface.

## Classify before you respond

| Class | Example | What the model should do | Action |
|---|---|---|---|
| **Recoverable, user-fixable** | Missing/invalid argument | Ask the user or re-call with corrected args | Return precise constraint text |
| **Recoverable, retryable** | 429, 503, timeout | Retry (or your tool already did) | Return `retryable: true`, hint on delay |
| **Recoverable, alternative** | Item out of stock, no results | Offer another tool/option | Return why + available options |
| **Terminal for this path** | Record doesn't exist | Stop; report honestly | Return not-found; don't imply otherwise |
| **Fatal** | Bug, bad config, auth misconfigured | Report a real problem | Raise; let your monitoring catch it |

The last row is the one people get wrong: swallowing configuration errors into `status: 'error'` turns an obvious deploy bug into a model that politely apologises all day while nobody gets paged.

## Error messages as repair instructions

A good tool error contains four things:

```python
return {
    'status': 'error',
    'error_message': "urgency must be an integer from 1 to 5; got 'high'.",
    'error_code': 'INVALID_ARGUMENT',
    'retryable': False,
    'hint': 'Map the description to a number: low=1, normal=3, high=5.',
}
```

1. **What was wrong** — the violated rule, not the exception class.
2. **What was given** (when it's safe to echo back).
3. **What correct looks like** — format, range, or source to get it from.
4. **Whether retrying helps.**

Rules of thumb:

- **Never say only "error".** The model will guess and often guess the same wrong way twice.
- **State provenance for IDs**: `"invoice_id must come from get_orders — INV-4821 is not a valid format"` prevents fabrication better than any system-prompt sentence.
- **Keep terminal answers terminal.** `"No invoice exists"` with `retryable: false` stops the loop; adding "please check the ID again" is fine, implying it might work next time is not.
- **Bound the loop.** If the same tool fails identically three times, that's a design bug — surface it to a callback layer rather than letting the model burn turns.

## Sanitise: errors are an exfiltration path

Raw exceptions leak. Connection errors embed URLs with credentials; validation errors can echo user input (including injected instructions); stack traces reveal internals. Before an error reaches the model:

```python
import logging, traceback

async def call_billing(**kwargs) -> dict:
    try:
        resp = await billing.post(**kwargs)
        return {'status': 'success', 'data': resp}
    except Exception:
        ref = uuid.uuid4().hex[:8]                 # correlation ID for humans
        logger.exception('billing tool failed ref=%s', ref)
        return {
            'status': 'error',
            'error_message': f'Billing service is unavailable (ref {ref}).',
            'retryable': True,
        }                                          # no URL, no token, no stack
```

Log the details for operators; return a correlatable, content-free message to the model. Note also that tool errors end up **persisted in session events** — anything you return is written down.

## Partial success is usually the honest answer

Batch-shaped tools rarely fail all-or-nothing:

```python
def import_contacts(rows: list[dict]) -> dict:
    """Import contacts from rows.

    Args:
        rows (list[dict]): Contact records with name and email fields.
    """
    ok, failed = [], []
    for i, row in enumerate(rows):
        try:
            contact = create_contact(row)
            ok.append(contact.id)
        except ValidationError as e:
            failed.append({'index': i, 'reason': str(e)})

    return {
        'status': 'success' if not failed else 'partial',
        'imported': len(ok),
        'failed': failed,
        'summary': f'Imported {len(ok)}/{len(rows)} contacts.'
                   + (f' Failed rows: {failed}.' if failed else ''),
    }
```

`status: 'partial'` lets the model report exactly what happened and decide whether to ask about the failed rows — without either pretending success or discarding the successful work.

## Observability and hooks

Every tool failure deserves a metric: per-tool error rate, error code distribution, and the share that reach the model. A sudden rise in `INVALID_ARGUMENT` after a deploy means your schema or prompt changed and the model no longer understands the contract.

ADK's callback and plugin layer lets you intercept tool execution — a `before_tool` hook can validate arguments early, and an `after_tool`/error path can normalise exceptions into your standard error envelope, so every tool in your codebase emits the same shape without duplicating try/except in fifty functions.

## Takeaways

- Errors reach the model either as a returned `status: 'error'` payload or as a raised exception the framework converts — pick by class: domain failures return, programming errors raise.
- Write errors as repair instructions: violated rule, what was given, what correct looks like, and whether retrying helps.
- Sanitise before returning — error text lands in the model's context *and* in persisted session events.
- Use `partial` status for batch work so partial progress is reported honestly.
- Track per-tool error rates as a first-class metric; they're your earliest signal of a broken contract.

## Further reading

- [Defining function tools: type hints, docstrings, and validation](/blog/adk-function-tools-type-hints-docstrings)
- [Handling agent exceptions and graceful fallback strategies](/blog/adk-agent-exceptions-graceful-fallback)
- [Rate limits (429) and exponential backoff](/blog/adk-rate-limits-429-exponential-backoff)
- [Extending the runner pipeline with custom middlewares and hooks](/blog/adk-runner-middleware-hooks)
