# Errors

Error response shapes, HTTP status codes, business error codes and retry rules for the FineProxy REST API, with ready-to-use error handling in Node.js and Python.

- Canonical: https://fineproxy.org/developers/docs/errors/

The FineProxy API uses standard HTTP status codes and returns a JSON body for every error. This page shows the shapes you will see, what each status means, which errors are safe to retry and how MCP reports errors differently.

## Error body shapes

Every error body is a JSON object. The reason is in one of three places.

**String `detail`** — the most common shape. The message is meant for humans and logs:

```json
{
  "detail": "Total order IP count (10) is below the tenant minimum of 100 IPs per order"
}
```

**Object `detail` with a machine-readable code** — used for business errors. The code is in `detail.error` (some endpoints use `detail.code`); `detail.message` explains it, and extra fields give context:

```json
{
  "detail": {
    "error": "GEO_COUNTS_MISMATCH",
    "requested": 1,
    "replaced": 100,
    "message": "geo_counts total (1) must equal the number of IPs being replaced (100)."
  }
}
```

**Top-level `error`** — the cancellation cooldown (`409 SERVICE_CANCEL_COOLDOWN`) returns the code at the top level of the body, together with a `retry_at` timestamp.

Validation errors (`422`) often carry only a generic message, without a list of fields:

```json
{
  "detail": "Validation error"
}
```

When you get a generic `422`, compare your request with the schema in the [API reference](/developers/docs/api/orders/): check field names, types, required fields and that you did not send unknown fields.

> **Note:** Branch your code on the HTTP status and the machine-readable code. Use the message text only for logs — it can change.

## HTTP status codes

| Status | Meaning | What to do |
| --- | --- | --- |
| `400 Bad Request` | The request is well-formed but cannot be processed as sent (for example, `"geo_counts must contain at least one country."`) | Fix the request. Do not retry unchanged. |
| `401 Unauthorized` | API key missing, malformed, invalid or revoked | Fix the `Authorization` header or replace the key. See [Authentication](/developers/docs/authentication/). |
| `402 Payment Required` | The wallet balance is too low for a paid operation; nothing is charged | Top up the wallet, then retry with the same idempotency key. |
| `403 Forbidden` | The action is not allowed for this caller: session-only endpoints (`api_key_management_requires_session`) or a payment gateway that needs identity verification first (`kyc_required`) | Use the dashboard, or follow the instructions in `detail`. Do not retry. |
| `404 Not Found` | The object does not exist in your account, the path is unknown, or the endpoint does not apply to this service type (for example, rotating config on a datacenter service) | Check the ID, the path and the service's `product_kind`. |
| `405 Method Not Allowed` | Wrong HTTP method; the `Allow` header lists the valid ones | Fix the method. |
| `409 Conflict` | The request conflicts with the current state: cancellation cooldown, price confirmation mismatch, idempotency key reused for a different request | Read the code in the body; re-quote, wait or use a new key as appropriate. |
| `422 Unprocessable Entity` | Validation failed or a business rule was violated (minimum order size, invalid IP, unknown field) | Fix the request. Do not retry unchanged. |
| `429 Too Many Requests` | Rate limit exceeded; body `{"detail": "Too Many Requests"}` | Back off and retry. See [Rate limits](/developers/docs/rate-limits/). |
| `503 Service Unavailable` | A dependency is temporarily unavailable (for example, a payment provider) | Retry later with backoff, or choose another option. |

## Business error codes

| Code or message | Status | Where | What to do |
| --- | --- | --- | --- |
| `api_key_management_requires_session` | 403 | `/api/v1/customers/me/api-keys` | Manage keys in [Settings → API keys](https://fineproxy.org/account_new/settings#api-keys). |
| `kyc_required` | 403 | `POST /api/v1/customer/wallet/deposit/init` | The chosen gateway needs identity verification; `detail.verification_url` points to it. Complete it in the dashboard or choose another gateway. |
| `Total order IP count (N) is below the tenant minimum of 100 IPs per order` | 422 | Composite quote, order, auto-plan, add-IPs quote | Order at least 100 IPs in total across all segments. |
| `GEO_COUNTS_MISMATCH` | 422 | `POST .../proxy/refresh/quote` | Make `geo_counts` add up to the number of IPs being replaced (`detail.replaced`). |
| `SERVICE_CANCEL_COOLDOWN` | 409 | `POST .../cancel` | Self-service cancellation is limited to once every 3 days per account. Wait until `retry_at` or open a support ticket. |
| `IDEMPOTENCY_KEY_REUSED` | 409 | `POST /api/v1/billing/composite/order` | The key was already used for a different order. Generate a new key for a new purchase. |
| `nowpayments_unavailable` | 503 | Crypto deposit coins and quotes | The crypto gateway is temporarily unavailable. Retry later or use another gateway. |
| `Rotating config not available for service <id>` | 404 | `GET .../proxy/config` | The service is not a rotating plan. Use `GET .../proxy/auth` for datacenter services. |

See [Idempotency & price guards](/developers/docs/idempotency/) for the price-confirmation errors returned by purchase endpoints.

## Which errors to retry

| Situation | Retry? |
| --- | --- |
| `429`, `503`, network error, timeout on a `GET` | Yes, with exponential backoff and jitter. |
| `429`, `503`, network error, timeout on a `POST` that spends money | Yes, but **only with the same idempotency key** — then a retry cannot charge twice. |
| `402` | After topping up the wallet, with the same idempotency key. |
| `409 SERVICE_CANCEL_COOLDOWN` | Not before `retry_at`. |
| `400`, `401`, `403`, `404`, `405`, `422`, other `409` | No. Change the request first. |

A timeout does not mean the request failed: the server may have completed it. For purchases, always retry with the same idempotency key instead of sending a new order.

## Handle errors in code

The helpers below normalize the three body shapes into one error object, retry `429` and `503` with backoff, and keep the request ID for support.

```javascript
const BASE = 'https://fineproxy.org/account_new/api/v1';

export class FineProxyError extends Error {
  constructor(status, code, message, requestId, body) {
    super(`FineProxy ${status}${code ? ` ${code}` : ''}: ${message}`);
    Object.assign(this, { status, code, requestId, body });
  }
}

function parseError(body) {
  if (typeof body?.detail === 'string') return { code: null, message: body.detail };
  if (body?.detail && typeof body.detail === 'object') {
    return { code: body.detail.error ?? body.detail.code ?? null, message: body.detail.message ?? JSON.stringify(body.detail) };
  }
  if (body?.error) return { code: body.error, message: body.message ?? body.error };
  return { code: null, message: JSON.stringify(body) };
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Retries only when it is safe: GET requests, or bodies that carry an idempotency key.
export async function fineproxy(path, { method = 'GET', body, retries = 4 } = {}) {
  const safeToRetry = method === 'GET' || Boolean(body?.idempotency_key);
  for (let attempt = 0; ; attempt++) {
    let res;
    try {
      res = await fetch(`${BASE}${path}`, {
        method,
        headers: {
          Authorization: `Bearer ${process.env.FINEPROXY_API_KEY}`,
          ...(body ? { 'Content-Type': 'application/json' } : {}),
        },
        body: body ? JSON.stringify(body) : undefined,
        signal: AbortSignal.timeout(60_000),
      });
    } catch (err) {
      if (safeToRetry && attempt < retries) { await sleep(1000 * 2 ** attempt + Math.random() * 500); continue; }
      throw err;
    }
    if (res.ok) return res.status === 204 ? null : res.json();

    const errBody = await res.json().catch(() => ({}));
    const { code, message } = parseError(errBody);
    if ((res.status === 429 || res.status === 503) && safeToRetry && attempt < retries) {
      await sleep(1000 * 2 ** attempt + Math.random() * 500);
      continue;
    }
    throw new FineProxyError(res.status, code, message, res.headers.get('x-request-id'), errBody);
  }
}
```

```python
import os
import random
import time

import requests

BASE = "https://fineproxy.org/account_new/api/v1"


class FineProxyError(Exception):
    def __init__(self, status, code, message, request_id, body):
        super().__init__(f"FineProxy {status}{' ' + code if code else ''}: {message}")
        self.status, self.code, self.request_id, self.body = status, code, request_id, body


def parse_error(body):
    detail = body.get("detail") if isinstance(body, dict) else None
    if isinstance(detail, str):
        return None, detail
    if isinstance(detail, dict):
        return detail.get("error") or detail.get("code"), detail.get("message") or str(detail)
    if isinstance(body, dict) and body.get("error"):
        return body["error"], body.get("message") or body["error"]
    return None, str(body)


def fineproxy(path, method="GET", body=None, retries=4):
    """Retries only when it is safe: GET requests, or bodies that carry an idempotency key."""
    safe_to_retry = method == "GET" or bool(body and body.get("idempotency_key"))
    for attempt in range(retries + 1):
        try:
            res = requests.request(
                method,
                f"{BASE}{path}",
                headers={"Authorization": f"Bearer {os.environ['FINEPROXY_API_KEY']}"},
                json=body,
                timeout=60,
            )
        except requests.RequestException:
            if safe_to_retry and attempt < retries:
                time.sleep(2 ** attempt + random.random() / 2)
                continue
            raise
        if res.ok:
            return None if res.status_code == 204 else res.json()

        try:
            err_body = res.json()
        except ValueError:
            err_body = {}
        code, message = parse_error(err_body)
        if res.status_code in (429, 503) and safe_to_retry and attempt < retries:
            time.sleep(2 ** attempt + random.random() / 2)
            continue
        raise FineProxyError(res.status_code, code, message, res.headers.get("x-request-id"), err_body)
```

Use it like this:

```javascript
try {
  const quote = await fineproxy('/billing/composite/quote', {
    method: 'POST',
    body: { segments: [{ country: 'DE', count: 10 }], period_months: 1 },
  });
} catch (err) {
  if (err instanceof FineProxyError && err.status === 422) {
    console.error('Fix the request:', err.message, 'request id:', err.requestId);
  } else {
    throw err;
  }
}
```

```python
try:
    quote = fineproxy(
        "/billing/composite/quote",
        method="POST",
        body={"segments": [{"country": "DE", "count": 10}], "period_months": 1},
    )
except FineProxyError as err:
    if err.status == 422:
        print("Fix the request:", err, "request id:", err.request_id)
    else:
        raise
```

With 10 IPs the quote fails with the tenant-minimum `422`; with 100 IPs it succeeds.

## MCP errors

The MCP server reports errors at three levels:

- **Transport errors** are real HTTP statuses: `401` with `WWW-Authenticate: Bearer` for a missing or invalid key, and `429` with `{"detail": "Too Many Requests"}` on bursts. Handle them like REST errors.
- **Tool errors** — invalid arguments, business rules, price mismatches, cooldowns — come back as **HTTP 200** with `result.isError: true` and a text explanation in `result.content[0].text`. For example, `cancel_service` during the cooldown returns text that starts with `SERVICE_CANCEL_COOLDOWN:`.
- **Protocol errors** — an unknown JSON-RPC method or a batch request — come back as a JSON-RPC `error` object (for example, code `-32601` or `-32600`).

Always check `result.isError` before reading a tool result. See [MCP protocol details](/developers/docs/mcp/protocol/).

## Next steps

- [Rate limits](/developers/docs/rate-limits/) — avoid `429`.
- [Idempotency & price guards](/developers/docs/idempotency/) — retry purchases without double charges.
- [Conventions](/developers/docs/conventions/) — request IDs, money and pagination.
