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

# Error Handling

> Recover from TwexAPI HTTP errors, MCP tool failures, credit limits, and write-action retries.

TwexAPI returns errors at two layers: **MCP JSON-RPC errors** (authentication before a tool runs) and **REST HTTP errors** (after a request reaches the API). Preserve status codes, response bodies, cursors, and IDs so retries and human review stay safe.

## REST response envelope

Successful calls return:

```json theme={null}
{
  "code": 200,
  "msg": "success",
  "data": {}
}
```

When HTTP status is not `2xx`, treat the response as a failure even if the body includes a `code` field. Log the full body, the request path, and any cursor you already consumed.

## HTTP status recovery

| Status | Meaning                                                      | Action                                                                                                                |
| ------ | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `400`  | Invalid query, missing field, or malformed body              | Fix input. **Do not** retry unchanged.                                                                                |
| `401`  | Missing or invalid API key                                   | Replace the credential from the [dashboard](https://twexapi.io/dashboard). Check `Authorization: Bearer` formatting.  |
| `403`  | Credits exhausted, account restricted, or action not allowed | Check [Get Balance](/api-reference/balance-endpoints/get-balance). Top up or remove write steps until access returns. |
| `404`  | Tweet, user, list, or resource not found                     | Verify IDs, screen names, and cursor freshness.                                                                       |
| `422`  | Validation failed on structured input                        | Fix schema fields documented on the endpoint page. Do not retry unchanged.                                            |
| `429`  | Rate limit exceeded                                          | Back off using [Rate Limits](/guides/rate-limits). Preserve `next_cursor` and completed rows.                         |
| `5xx`  | Transient service or upstream fetch failure                  | Retry with exponential backoff and a hard cap.                                                                        |

## Credits and balance

Metered reads and writes spend account credits. When a job processes many pages, check balance before and after long runs:

```bash theme={null}
curl --request GET \
  --url 'https://api.twexapi.io/balance' \
  --header 'Authorization: Bearer YOUR_API_KEY'
```

If `403` responses mention credits or access:

1. Stop scheduled jobs that keep hammering the API.
2. Confirm balance in the dashboard.
3. Resume from the last saved cursor after credits are restored.

## Pagination-safe retries

For search, followers, timelines, and DM history:

* Store `next_cursor`, `has_next_page`, and any `task_id` outside the agent conversation.
* After `429` or `5xx`, retry the **same cursor**, not the next page.
* After `400`, `404`, or `422`, inspect IDs and query parameters before retrying.

## Write actions

Write endpoints (tweet, reply, like, follow, DM send) require:

* A valid TwexAPI API key
* A saved Twitter cookie or `auth_token` on the request

Recovery rules:

| Situation         | Action                                                                                         |
| ----------------- | ---------------------------------------------------------------------------------------------- |
| `401` on write    | Fix API key and cookie credentials before retrying.                                            |
| `403` on write    | Confirm credits and that the connected account still has permission.                           |
| Ambiguous success | Look up the tweet, DM, or engagement state with a read endpoint before duplicating the action. |
| Agent workflows   | Require human approval before any `read_only: false` MCP call.                                 |

TwexAPI does not expose a separate write-action polling API. Prefer idempotent read checks (tweet lookup, DM status) before repeating side effects. Cookie setup and `403` recovery: [Write Actions](/guides/write-actions).

## MCP errors

### Authentication failed before the tool ran

When MCP authentication fails, `explore` and `twexapi_request` do not execute:

```json theme={null}
{
  "jsonrpc": "2.0",
  "error": {
    "code": 401,
    "message": "Missing MCP API token"
  }
}
```

Fix `x-api-key` or `Authorization: Bearer` on the MCP client, then rerun the tool call.

### API error returned through `twexapi_request`

When the underlying REST call fails, preserve the tool result:

```json theme={null}
{
  "status_code": 403,
  "endpoint": "get_global_trending_tweets",
  "method": "GET",
  "path": "/twitter/global-trending/tweets",
  "result": {
    "detail": "Credits exhausted or action not allowed."
  }
}
```

Apply the same HTTP recovery table above. Do not ask the model to guess a new path—call `explore` again if the route may have changed.

## SDK and CLI errors

Generated SDKs map HTTP failures to language-native exceptions. Catch errors at the job boundary, log the status code and response body, and route `429`/`5xx` to retry policies.

Python example:

```python theme={null}
import requests

try:
    response = requests.get(
        "https://api.twexapi.io/balance",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        timeout=30,
    )
    response.raise_for_status()
except requests.HTTPError as exc:
    status = exc.response.status_code
    body = exc.response.text
    if status == 429:
        # Back off, preserve cursor, retry later
        ...
    elif status in (400, 404, 422):
        # Fix input; do not retry unchanged
        ...
    raise
```

See language-specific patterns on each [SDK page](/sdks).

## Retry backoff template

Use capped exponential backoff for `429` and `5xx`:

```python theme={null}
retry_delays_seconds = [5, 15, 45, 120]

for delay in retry_delays_seconds:
    response = call_twexapi()
    if response.ok:
        break
    if response.status_code in (429, 500, 502, 503, 504):
        time.sleep(delay)
        continue
    break  # 4xx other than 429: stop and fix input
```

Pair backoff with [Rate Limits](/guides/rate-limits) so scheduled jobs do not restart at full QPS immediately after a `429`.

## Framework-specific notes

| Runtime                                                 | Guidance                                                   |
| ------------------------------------------------------- | ---------------------------------------------------------- |
| [LangChain](/guides/langchain)                          | Validate handoff models; stop the graph on `401`.          |
| [Prefect](/guides/prefect)                              | Use task retries with jitter; store cursors in task state. |
| [n8n / Zapier / Make](/guides/no-code-workflow-handoff) | Route `401`/`403` to ops alerts; delay `429` replays.      |
| [MCP agents](/mcp/agent-handoff)                        | Never discard `next_cursor` after partial success.         |

## Related pages

* [Rate Limits](/guides/rate-limits)
* [Authentication](/authentication)
* [API Overview](/api-reference/overview)
* [MCP Tools](/mcp/tools)
