# Error Handling (https://docs.predictorsdk.com/guides/error-handling)

What every error looks like, what each status code means, and when to retry.

When a request fails, the API answers with an HTTP status code and a JSON body that says what went wrong.

## Error response format [#error-response-format]

Every error, on every endpoint, has the same body:

```json
{
  "code": "invalid_parameter",
  "message": "invalid provider \"sx_bet\": must be one of kalshi, polymarket, predict, sxbet, hyperliquid, alpha-arcade, prophetx, limitless, pred, polymarket-us",
  "status_code": 400,
  "param": "provider"
}
```

- **`code`** is a stable machine-readable reason. Branch on it: a code is never
  renamed or reused, and new ones may be added.
- **`message`** says what went wrong and how to fix it, for people. It quotes the
  value you sent where there is one. Show it or log it; do not parse it.
- **`status_code`** repeats the HTTP status, for logs that keep only the body.
- **`param`** names the query or path parameter the error concerns, when there is
  one.
- **`errors`** lists every problem when a request has more than one, such as a
  lookup batch with several bad identifiers. `message` describes the first:

```json
{
  "code": "invalid_parameter",
  "message": "invalid source_id \"kalshi:yes\": \"yes\" names a side within one kalshi market, not a market; look the market up by its market_id (and 1 more problem; see errors)",
  "status_code": 400,
  "param": "source_id",
  "errors": [
    { "param": "source_id", "value": "kalshi:yes", "message": "invalid source_id \"kalshi:yes\": …" },
    { "param": "source_id", "value": "bogus:1", "message": "invalid source_id \"bogus:1\": must be {provider}:{id}, …" }
  ]
}
```

A `409` adds `candidates` and a `402` adds `action`, `required_tier` and
`current_tier` (see below).

## Request ids [#request-ids]

Every response, a success or any error, carries an `X-Request-Id` header: a
short opaque string that names that one request. When a call fails or surprises
you, quote the id when you contact support and we can find the request from it.
Log it beside the status code of any request you may need to ask about.

- The API generates it for every request, so a retry of a failed request gets a
  new one.
- It is opaque. Do not parse it or rely on its length or prefix.
- The API ignores an `X-Request-Id` you send and does not echo it back, so it is
  not a way to tag your own requests.

Every SDK error carries the response headers; see
[Reading the request id](https://docs.predictorsdk.com/guides/error-handling#reading-the-request-id).

## Status codes [#status-codes]

| Status | `code` | Meaning |
|---|---|---|
| `400` | `unknown_parameter` | The endpoint does not read that query parameter. `message` lists the ones it accepts |
| `400` | `invalid_parameter` | A value is malformed, empty, out of range, sent more than once, or contradicts another parameter (e.g. a `source_id` without its `{provider}:` prefix) |
| `400` | `missing_parameter` | A required parameter is absent |
| `400` | `invalid_cursor` | A `cursor` that is malformed, stale, or from another endpoint or filter set. Start again without it |
| `400` | `invalid_identifier` | A `market_id` or `event_id` that cannot exist on the provider it resolves to, or whose `{provider}:` prefix names no provider |
| `400` | `upstream_rejected` | The venue rejected the request |
| `401` | `missing_api_key` | No `Authorization: Bearer <key>` header. `message` says what was sent instead, if anything |
| `401` | `invalid_api_key` | The key is not valid, including any key longer than 256 characters |
| `402` | `payment_required` | The free monthly allowance is used up, or a paid subscription has a payment problem. See [Plans & Limits](https://docs.predictorsdk.com/guides/plans) |
| `403` | `forbidden` | The key lacks the permission this endpoint requires |
| `404` | `route_not_found` | No route matches the path. Check the path before you check the ID |
| `404` | `market_not_found` | The market does not exist on the selected or inferred provider |
| `404` | `event_not_found` | The event does not exist on the selected or inferred provider |
| `404` | `profile_not_found` | No Polymarket profile matches the address or username |
| `405` | `method_not_allowed` | The path exists, but not with the HTTP method you sent. The `Allow` header lists the right ones |
| `409` | `ambiguous_identifier` | A bare `market_id` or `event_id` exists on more than one venue, so the API won't guess which you meant. See [Always send the provider](https://docs.predictorsdk.com/concepts/events-and-markets#always-send-the-provider) |
| `429` | `rate_limited` | The key exceeded its per-minute limit. Honour `Retry-After` |
| `429` | `usage_limit_exceeded` | The key used up an allowance that does not refill within the minute |
| `429` | `upstream_rate_limited` | The venue rate-limited the request |
| `502` | `upstream_unavailable` | PredictorSDK could not get a valid response from a venue or from API-key verification |
| `503` | `service_unavailable` | A reader, service dependency, or endpoint configuration is temporarily unavailable |

### Routing errors [#routing-errors]

These come from the router rather than from an endpoint. They can arrive on
any path, and none needs a valid API key: the router answers before it reads
the key.

- A path matching **no route** returns `404` with code `route_not_found`. An
  endpoint's own `404` (`market_not_found`, `event_not_found`) means the
  identifier was looked up and missed.
- A path that exists but **not under the method you sent** returns `405` with
  code `method_not_allowed`, an `Allow` header naming the methods that path does
  accept, and the same list in `message`. Every endpoint in these docs is a
  `GET`.
- A request carrying a **query parameter the endpoint does not read** returns
  `400` with code `unknown_parameter`. One that sends a parameter twice (other
  than the repeatable `event_id` and `source_id` of the matching lookup), or a
  filter or identifier with an empty value, returns `400` with code
  `invalid_parameter`.
- A **query string that is not `&`-separated `key=value` pairs** returns `400`
  with code `invalid_parameter`, quoting the pair at fault: a `;` used as a
  separator, or a `%` not followed by two hex digits. Percent-encode a literal
  `;` as `%3B` and `%` as `%25`.

A generated SDK method sends its own declared path and method, so it never
meets the `404` or `405`. Every operation declares `400`, so the parameter
rejections arrive as that operation's typed bad-request error.

#### Unknown, repeated and empty parameters are rejected, not ignored [#unknown-repeated-and-empty-parameters-are-rejected-not-ignored]

Every parameter you send has to be one the endpoint reads, sent once (the
lookup's `event_id` and `source_id` can repeat), and a filter or ID needs a
value. This is on purpose and holds on every route: a silently dropped
parameter returns a full, unfiltered response that *looks* filtered, which is
much harder to spot than an error. For example, `?platform=` on
[`GET /v1/markets`](https://docs.predictorsdk.com/api-reference/getMarkets), a natural guess for a venue
filter, or `?provider=` left empty by a template:

```
GET /v1/markets?platform=sxbet
400 {"code": "unknown_parameter",
     "message": "This endpoint does not read the query parameter \"platform\". It accepts: category, cursor, limit, provider.",
     "status_code": 400, "param": "platform", "errors": [...]}
```

The parameter to use there is `provider`; see [Filtering](https://docs.predictorsdk.com/guides/filtering).
The SDKs only send the parameters each method declares, unless you add others
through their raw request options.

A parameter the API renamed answers the same `400` and names its replacement,
so an old request learns the new spelling from the error. `platform` became
`provider` on market detail and events, and the crypto-prices `pagination_key`
became `cursor`:

```
GET /v1/events/predict:1607914?platform=predict
400 {"code": "unknown_parameter",
     "message": "This endpoint does not read the query parameter \"platform\". It accepts: provider. \"platform\" was replaced by ?provider={provider}, which takes the same values.",
     "status_code": 400, "param": "platform", "errors": [...]}
```

## Rate-limit headers [#rate-limit-headers]

Authenticated responses include the current key's rate-limit state:

| Header | Unit | Meaning |
|---|---|---|
| `X-RateLimit-Limit` | requests | Requests allowed in a 60-second window. Equals your plan's `rate_limit_per_min` from `GET /v1/plans` |
| `X-RateLimit-Remaining` | requests | **A rough estimate,** not a countdown. See below |
| `X-RateLimit-Reset` | Unix seconds | End of the current window. A step function: the same value on every response inside one window |
| `Retry-After` | seconds | Whole seconds to wait; included on API-key `429` responses and optional on upstream `429` responses |

Responses that need no key (`GET /v1/plans`, and the router's `404` and `405`
above) carry none of them, because the limiter only runs once a key is read.

`X-RateLimit-Reset` is a Unix epoch in **seconds**, not milliseconds. The
generated SDK retry layers accept both the documented seconds form and the
legacy millisecond epoch that older deployments emitted. They cap retry delays
at 60 seconds and retry `408`, `429`, and `5xx` responses (never a `409`, which
answers the same way every time).

### Building a local limiter [#building-a-local-limiter]

**Don't pace from `X-RateLimit-Remaining`.** The budget refills gradually as
older requests age out, so the value can repeat, skip, or even go up between
two requests in a row. It also tends to run ahead of what you have actually
spent, most of all during a fast burst, which is exactly when you would look at
it. Treat a low value as a reason to slow down, never a high one as permission
to speed up.

Two things follow that surprise people used to fixed windows:

- `X-RateLimit-Reset` is **not a refill moment**. Nothing jumps back to
  `X-RateLimit-Limit` when it passes. Use it as the longest a `429` can last.
- Spending `X-RateLimit-Limit` requests at once and then waiting for
  `X-RateLimit-Reset` doesn't work. Spread the same budget over a rolling 60
  seconds.

What works is a sliding window in your own client, which needs nothing from
`X-RateLimit-Remaining`:

1. Read `rate_limit_per_min` for your plan from `GET /v1/plans`, or take
   `X-RateLimit-Limit` from any authenticated response. They are the same
   number.
2. Keep the times of your last 60 seconds of requests, and hold off when that
   count reaches the limit. Or space requests `60 / limit` seconds apart, which
   comes to the same thing without the bookkeeping.
3. When a `429` arrives, back off for `Retry-After` seconds. The `429` and
   `Retry-After` are the final word, and they always agree with
   `X-RateLimit-Reset`.

### `402 Payment Required` response [#402-payment-required-response]

The response body includes an `action` field so clients can render the right follow-up:

| `action` | Meaning | Recommended UX |
|---|---|---|
| `upgrade_plan` | The caller is on a lower tier than the endpoint requires, or a Free caller exhausted the monthly request allowance. | Route them to `/pricing` or a plan-upgrade CTA. |
| `resolve_payment` | The caller had a paid subscription that now has a payment problem (`past_due`, `unpaid`, `paused` or `incomplete`), so the account is back on Free. | Send them to the billing page in the dashboard to fix the payment. |

Both variants return the same `402` status and include `required_tier` / `current_tier` so clients can keep a single handler with an `action` switch inside.

When a Free caller exhausts the monthly allowance, the response also includes `included_requests_per_month` and `current_period_requests`.

## Handling errors in the SDK [#handling-errors-in-the-sdk]

Every SDK throws a typed error for each documented status code. `PaymentRequiredError` (the `402`) carries `action`, `required_tier` and `current_tier` on its body, and `included_requests_per_month` and `current_period_requests` when the free allowance ran out.

  **TypeScript**
    ```ts
    import { PredictorSDK, PredictorSDKClient } from "@predictorsdk/client";

    const client = new PredictorSDKClient({
      token: "YOUR_API_KEY",
    });

    try {
      // A venue ID without its provider prefix is a 400.
      await client.lookupSportsMatchingMarkets({ sourceId: "KXNBAGAME-26OCT20OKCSAS" });
    } catch (error) {
      if (error instanceof PredictorSDK.BadRequestError) {
        console.log("Bad request:", error.body.code, error.body.message);
      } else if (error instanceof PredictorSDK.PaymentRequiredError) {
        if (error.body.action === "resolve_payment") {
          // The subscription has a payment problem: send them to billing
        } else {
          // Over the plan or allowance: send them to /pricing
        }
      } else if (error instanceof PredictorSDK.TooManyRequestsError) {
        // Rate limited: back off, then retry
      } else if (error instanceof PredictorSDK.UnauthorizedError) {
        // Invalid API key
      }
    }
    ```
    **Python**
    ```python
    from predictorsdk import PredictorSDK, BadRequestError, PaymentRequiredError

    client = PredictorSDK(token="YOUR_API_KEY")

    try:
        # A venue ID without its provider prefix is a 400.
        client.lookup_sports_matching_markets(source_id="KXNBAGAME-26OCT20OKCSAS")
    except BadRequestError as e:
        print(f"Bad request: {e.body.code}: {e.body.message}")
    except PaymentRequiredError as e:
        if e.body.action == "resolve_payment":
            # The subscription has a payment problem: send them to billing
            ...
        else:
            # Over the plan or allowance: send them to /pricing
            ...
    ```
    **Go**
    ```go
    import (
        "context"
        "errors"
        "fmt"

        predictorclient "github.com/PredictorSDK/sdk-go/client"
        predictorsdk "github.com/PredictorSDK/sdk-go"
        "github.com/PredictorSDK/sdk-go/option"
    )

    func main() {
        client := predictorclient.New(option.WithToken("YOUR_API_KEY"))

        // A venue ID without its provider prefix is a 400.
        _, err := client.LookupSportsMatchingMarkets(context.TODO(), &predictorsdk.LookupSportsMatchingMarketsRequest{
            SourceID: []*string{predictorsdk.String("KXNBAGAME-26OCT20OKCSAS")},
        })
        var badReq *predictorsdk.BadRequestError
        var payReq *predictorsdk.PaymentRequiredError
        switch {
        case errors.As(err, &badReq):
            fmt.Println("Bad request:", badReq.Body.Code, badReq.Body.Message)
        case errors.As(err, &payReq):
            if payReq.Body.Action == predictorsdk.PaymentRequiredErrorActionResolvePayment {
                // The subscription has a payment problem: send them to billing
            } else {
                // Over the plan or allowance: send them to /pricing
            }
        }
    }
    ```
  
### Reading the request id [#reading-the-request-id]

Each SDK exposes the response headers on its errors, so the id is one lookup
away. It is missing only when no response arrived at all (a timeout, or a
connection that failed), because then there is no request on our side to name.

  **TypeScript**
    ```ts
    import { PredictorSDKError } from "@predictorsdk/client";

    try {
      await client.getCategories();
    } catch (error) {
      if (error instanceof PredictorSDKError) {
        // The `x-request-id` response header; undefined when no response arrived.
        console.log(error.statusCode, error.requestId);
      }
    }
    ```
    **Python**
    ```python
    from predictorsdk.core.api_error import ApiError

    try:
        client.get_categories()
    except ApiError as e:
        # `headers` holds the response headers with lower-case names.
        print(e.status_code, (e.headers or {}).get("x-request-id"))
    ```
    **Go**
    ```go
    import (
        "errors"

        "github.com/PredictorSDK/sdk-go/core"
    )

    _, err := client.GetCategories(ctx)
    var apiErr *core.APIError
    if errors.As(err, &apiErr) {
        // Every typed error (BadRequestError, NotFoundError, ...) wraps *core.APIError.
        fmt.Println(apiErr.StatusCode, apiErr.Header.Get("X-Request-Id"))
    }
    ```
  
## Retry guidance [#retry-guidance]

- **429**: wait for `Retry-After`, or if it is missing, until
  `X-RateLimit-Reset` (in seconds). Add jitter only when many clients share a
  key. Don't decide when to send from `X-RateLimit-Remaining`; see
  [Building a local limiter](https://docs.predictorsdk.com/guides/error-handling#building-a-local-limiter).
- **502/503**: a venue or a dependency failed for a moment. Retry with
  exponential backoff, up to what your application can wait.
- **404**: don't retry as is. Check the ID, and pass `provider` when the ID
  could belong to more than one venue. `route_not_found` means the path itself
  is wrong; `market_not_found` and `event_not_found` mean the ID wasn't found.
- **405**: don't retry as is. Send it again with a method from the `Allow`
  header.
- **409**: don't retry as is; the same request conflicts again. Send it with
  `?provider=` set to one of the `candidates` in the body, or use the composite
  `{provider}:{id}` form.
- **400/401/402/403**: don't retry. Fix the request, the plan, the permission
  or the key.