Skip to content
Twexapi
English
Esc
↑↓navigate↵open⌘Jpreview
On this page

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:

{
  "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. Check Authorization: Bearer formatting.
403 Credits exhausted, account restricted, or action not allowed Check 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. 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:

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.

Prefer idempotent read checks (tweet lookup, profile about) before repeating requests. See Rate Limits for backoff.

MCP errors

Authentication failed before the tool ran

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

{
  "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:

{
  "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:

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.

Retry backoff template

Use capped exponential backoff for 429 and 5xx:

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 so scheduled jobs do not restart at full QPS immediately after a 429.

Framework-specific notes

Runtime Guidance
LangChain Validate handoff models; stop the graph on 401.
Prefect Use task retries with jitter; store cursors in task state.
n8n / Zapier / Make Route 401/403 to ops alerts; delay 429 replays.
MCP agents Never discard next_cursor after partial success.

Was this page helpful?