> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/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

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

```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.gateway.unicode_utils import safe_error_message; print('OK')"
    ```

    If this runs without error, you have the fix from PR #1754.
  </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

***

## 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>

***

## 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 symbol |
| `✓`     | `OK`     | Check mark     |
| `✗`     | `X`      | Cross mark     |
| `→`     | `->`     | Right arrow    |
| `…`     | `...`    | Ellipsis       |
| `"` `"` | `"`      | Smart quotes   |
| `—` `–` | `--` `-` | Em/en dash     |

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.
```

***

## 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="/guides/troubleshoot-gateway">
    Troubleshoot Windows charmap errors and other gateway issues
  </Card>

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