> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Gateway Error Handling

> Unicode-safe error handling for Gateway bot replies with root-cause extraction

<Note>
  The gateway now ships in the `praisonai-bot` package. `praisonai serve gateway` still works exactly as documented here; for a standalone install see [praisonai-bot Migration](/docs/guides/praisonai-bot-migration).
</Note>

Gateway error handling automatically sanitises exception text to prevent encoding crashes while preserving meaningful error information for users.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    instructions="Help the user",
    model="gpt-4o-mini",
)
# Gateway bots receive clean ASCII-safe errors — not raw stack traces
agent.start("What's the weather?")
```

The user sends a message that triggers an internal error; the gateway sanitises the exception to ASCII-safe text in the reply while logging full detail.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Error Handling Flow"
        Exception[⚠️ Exception] --> Extract[🔍 Extract Root Cause]
        Extract --> Sanitize[🔧 Sanitize to ASCII]
        Sanitize --> Reply[💬 User Reply]
        Exception --> Log[📝 Full Unicode Log]
    end
    
    classDef error fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    classDef log fill:#6366F1,stroke:#7C90A0,color:#fff
    
    class Exception error
    class Extract,Sanitize process
    class Reply output
    class Log log

```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    Error handling is automatic — no configuration needed. When agents throw exceptions containing Unicode characters, the gateway safely converts them for bot replies.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="Assistant",
        instructions="Help the user",
        model="gpt-4o-mini"
    )
    # When the agent hits an API error (quota, rate limit, auth, timeout),
    # the gateway sends the user a clean message — not a stack trace.
    agent.start("What's the weather?")
    ```
  </Step>

  <Step title="Test Error Handling">
    Verify your version includes Unicode-safe error handling:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    python -c "from praisonai_bot.gateway.unicode_utils import safe_error_message; print('OK')"
    ```

    If this runs without error, your install includes the ASCII-safe error sanitizer (originally PraisonAI PR #1754; extended in PR #3430 to strip box-drawing frame characters).
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Bot
    participant Gateway
    participant Agent
    
    User->>Bot: Send message
    Bot->>Gateway: Forward to agent
    Gateway->>Agent: Process request
    Agent-->>Gateway: Exception with Unicode (⚠️ quota exceeded)
    Gateway->>Gateway: Extract root cause
    Gateway->>Gateway: Sanitize to ASCII-safe text
    Gateway-->>Bot: "API quota exceeded. Check billing."
    Bot-->>User: Clean error message
```

The gateway processes exceptions in three stages:

1. **Root-cause extraction** — identifies the underlying API error
2. **Unicode sanitization** — converts symbols to ASCII-safe equivalents
3. **Safe reply** — sends clean message to user via bot

### Related Helpers

The `unicode_utils` module exports two sibling helpers alongside `safe_error_message`.

| Helper                                | Purpose                                                                                                                                                  |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `safe_log_message(exc)`               | Preserves Unicode for UTF-8-capable log handlers, replacing lone surrogates (U+D800–U+DFFF) with U+FFFD. Use it for logs instead of user-facing replies. |
| `extract_root_cause_from_error(text)` | Pulls the underlying API error out of chained exceptions before sanitising — this powers the Recognized Error Types table below.                         |

***

## Configuration Options

Error handling is automatic with no required configuration. The feature is included in PraisonAI versions containing PR #1754.

<Card title="Gateway Error Handling Reference" icon="code" href="https://github.com/MervinPraison/PraisonAI/pull/1754">
  Source implementation details in PraisonAI PR #1754
</Card>

***

## Structured Connection Errors

The `hello` handshake returns machine-readable `ConnectErrorCode` values (`auth_required`, `auth_unauthorized`, `protocol_unsupported`, `pairing_required`, `agent_not_found`) with optional `next_action` hints — instead of free-text-only connection failures.

Codes fall into two client-side classes: **transient** (`rate_limited` — back off and retry) and **terminal** (`auth_required`, `auth_unauthorized`, `pairing_required`, `protocol_unsupported`, `agent_not_found`, `origin_not_allowed`, `configuration_error` — reconnect loop stops until an operator intervenes). See [Gateway Client → Terminal vs Transient Connect Errors](/docs/docs/features/gateway-client#terminal-vs-transient-connect-errors) for how `GatewayClient` handles each class and the `on_reconnect_paused` callback.

See [Gateway Handshake Protocol](/docs/features/gateway-handshake-protocol) for the full error matrix and capability negotiation.

***

## Reconnect After Disconnect

Pending inbox messages and in-flight executions are preserved when a WebSocket disconnects. On reconnect with the same `session_id`, the client receives a `status` frame:

```json theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{
  "type": "status",
  "message": "Resuming processing (2 pending messages)..."
}
```

Queued messages are processed in FIFO order. See [Gateway Session Continuity](/docs/features/gateway-session-continuity) for drain behaviour and persisted session shape.

***

## Common Patterns

### Recognized Error Types

The gateway automatically recognizes and formats these error patterns:

| Pattern matched in exception               | User-facing reply                       |
| ------------------------------------------ | --------------------------------------- |
| `Error code: <N> - <msg>` (OpenAI format)  | `Error <N>: <msg>`                      |
| `HTTP <N>: <msg>`                          | `Error <N>: <msg>`                      |
| Contains `quota` (exceeded / insufficient) | `API quota exceeded. Check billing.`    |
| Contains `rate limit` (exceeded)           | `Rate limit exceeded. Try again later.` |
| Contains `authentication` (failed)         | `Authentication failed. Check API key.` |
| Contains `timeout`                         | `Request timeout. Try again.`           |
| (anything else)                            | Original error text, sanitized to ASCII |

### Symbol Replacements

Unicode symbols are replaced with ASCII equivalents:

| Unicode                       | ASCII   | Description                                                                                                                                                          |
| ----------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `⚠`                           | `!`     | Warning sign                                                                                                                                                         |
| `✓`                           | `OK`    | Check mark                                                                                                                                                           |
| `✗`                           | `X`     | Ballot X                                                                                                                                                             |
| `→`                           | `->`    | Right arrow                                                                                                                                                          |
| `←`                           | `<-`    | Left arrow                                                                                                                                                           |
| `•`                           | `*`     | Bullet                                                                                                                                                               |
| `®`                           | `(R)`   | Registered sign                                                                                                                                                      |
| `©`                           | `(C)`   | Copyright sign                                                                                                                                                       |
| `…`                           | `...`   | Horizontal ellipsis                                                                                                                                                  |
| `"` `"`                       | `"`     | Smart double quotes                                                                                                                                                  |
| `'` `'`                       | `'`     | Smart single quotes                                                                                                                                                  |
| `–`                           | `-`     | En dash                                                                                                                                                              |
| `—`                           | `--`    | Em dash                                                                                                                                                              |
| `─ ━ │ ┃ ═ ║ ╔ ╗ ╚ ╝ ┌ ┐ └ ┘` | `space` | Box-drawing frame characters (e.g. Playwright's `playwright install` banner) — replaced with spaces so the actionable hint stays readable on Windows cp1252 consoles |

Accented letters (á, é, ñ, etc.) are converted to their base forms (a, e, n).

### Before vs After

**Before PR #1754 (broken on Windows):**

```
User sees: 'charmap' codec can't encode character '⚠' in position 27: character maps to <undefined>
```

**After PR #1754 (safe on all platforms):**

```
User sees: API quota exceeded. Check billing.
```

**Before PR #3430 (cluttered `?` placeholders around the frame on Windows cp1252):**

```
User sees: ? Please run: playwright install ?
```

**After PR #3430 (frame collapses to spaces, hint stays readable):**

```
User sees: Please run: playwright install
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Monitor Gateway Logs">
    Full Unicode exception details are preserved in gateway logs for debugging while users see clean ASCII-safe messages.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai gateway logs
    ```
  </Accordion>

  <Accordion title="Handle API Quota Limits">
    Set up billing alerts and monitor usage to prevent quota exceeded errors:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Users see: "API quota exceeded. Check billing."
    # Solution: Add credits at platform.openai.com
    ```
  </Accordion>

  <Accordion title="Test Cross-Platform Compatibility">
    The Unicode-safe error handling works on Windows, macOS, and Linux:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Test with Unicode in agent instructions or error messages
    agent = Agent(
        name="Test",
        instructions="Handle errors with Unicode: ⚠️ warnings, ✅ success",
        model="gpt-4o-mini"
    )
    ```
  </Accordion>

  <Accordion title="Upgrade Legacy Environments">
    No workaround needed on supported versions. Previously recommended environment variables (`PYTHONUTF8=1`) are no longer required for the bot reply path.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Gateway Troubleshooting" icon="wrench" href="/docs/guides/troubleshoot-gateway">
    Troubleshoot Windows charmap errors and other gateway issues
  </Card>

  <Card title="Bot Gateway" icon="server" href="/docs/features/bot-gateway">
    Configure multiple bots with the gateway server
  </Card>

  <Card icon="triangle-exclamation" href="/docs/features/failure-reply">
    User-facing reply for a failed agent turn, keyed by failure class
  </Card>
</CardGroup>
