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

# Error Handling

> How to handle errors from the iNwealth API

# Error Handling

The iNwealth API returns errors in two ways depending on when they occur:

* **Before streaming starts** — standard HTTP JSON errors
* **During streaming** — SSE error events

## HTTP errors

These are returned as standard JSON responses before any streaming begins.

### 401 — Authentication failed

```json theme={null}
{
  "detail": "Authentification requise"
}
```

Causes:

* Missing `Authorization` header
* Invalid or revoked API key
* Malformed Bearer token

### 400 — Invalid parameters

```json theme={null}
{
  "detail": "Invalid effort: xyz. Must be one of ['low', 'medium', 'high', 'max']"
}
```

Returned when a parameter has an invalid value (e.g. unsupported `effort` level).

### 422 — Missing required fields

```json theme={null}
{
  "detail": [
    {
      "type": "missing",
      "loc": ["body", "messages"],
      "msg": "Field required"
    }
  ]
}
```

Returned when required fields (`messages`, `session_id`) are missing or have the wrong type.

## SSE error events

Some errors occur **after the stream has started** (HTTP 200 already sent). These are delivered as SSE events:

### 429 — Rate limit exceeded

```
event: error
data: {"type": "error", "data": {"error": "Limite quotidienne organisation atteinte (1,000,000 tokens). Reset dans 3h42.", "error_type": "RateLimitExceeded"}}
```

Your organization's daily token quota has been exhausted. The error message includes the time until reset (midnight UTC).

### 500 — Internal error

```
event: error
data: {"type": "error", "data": {"error": "Erreur interne du serveur"}}
```

An unexpected server-side error occurred during response generation. If this persists, contact your account manager.

## Handling errors in code

### JavaScript

```javascript theme={null}
const response = await fetch("https://api.inwealth.fr/api/agent", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer sk_live_your_key_here"
  },
  body: JSON.stringify({
    messages: [{ role: "user", content: "Your question" }],
    session_id: "session-001"
  })
});

// Handle HTTP errors (401, 400, 422)
if (!response.ok) {
  const error = await response.json();
  console.error(`HTTP ${response.status}:`, error.detail);
  return;
}

// Handle SSE stream (including SSE error events)
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  for (const line of chunk.split("\n")) {
    if (!line.startsWith("data: ")) continue;
    const data = JSON.parse(line.slice(6));

    if (data.type === "error") {
      // SSE error (429 rate limit, 500 internal)
      console.error(data.data.error);
      if (data.data.error_type === "RateLimitExceeded") {
        // Wait until quota resets at midnight UTC
      }
      return;
    }

    if (data.type === "delta" && data.delta?.content) {
      // Normal delta — append to display
    }
  }
}
```

### Python

```python theme={null}
import httpx
import json

with httpx.stream(
    "POST",
    "https://api.inwealth.fr/api/agent",
    headers={"Authorization": "Bearer sk_live_your_key_here"},
    json={
        "messages": [{"role": "user", "content": "Your question"}],
        "session_id": "session-001",
    },
) as response:
    # Handle HTTP errors
    if response.status_code != 200:
        print(f"HTTP {response.status_code}: {response.read()}")
    else:
        # Handle SSE stream
        for line in response.iter_lines():
            if not line.startswith("data: "):
                continue
            data = json.loads(line[6:])
            if data.get("type") == "error":
                print(f"SSE error: {data['data']['error']}")
                break
```

## Summary

| Code  | Type      | When          | Format                                  |
| ----- | --------- | ------------- | --------------------------------------- |
| `401` | HTTP      | Before stream | `{"detail": "..."}`                     |
| `400` | HTTP      | Before stream | `{"detail": "..."}`                     |
| `422` | HTTP      | Before stream | `{"detail": [...]}`                     |
| `429` | SSE event | During stream | `event: error` with `RateLimitExceeded` |
| `500` | SSE event | During stream | `event: error`                          |
