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

# Handling Errors

> Comprehensive guide to error codes and troubleshooting for Topsort's APIs

# Errors

When working with Topsort's APIs, you may encounter various error responses. This guide helps you understand, diagnose, and resolve common issues.

## Error Response Format

Topsort APIs return errors as JSON arrays containing error objects:

| Field     | Type   | Description                                                |
| :-------- | :----- | :--------------------------------------------------------- |
| `errCode` | string | Short string uniquely identifying the problem              |
| `docUrl`  | string | Link to documentation providing more information           |
| `message` | string | Optional human-readable explanation (may change over time) |

## HTTP Status Codes

<CardGroup cols={2}>
  <Card title="400 - Bad Request" icon="circle-exclamation">
    Unacceptable request format or incorrect syntax. Check request structure against API spec.
  </Card>

  <Card title="403 - Forbidden" icon="lock">
    API key issue or missing authorization tokens. Verify your authentication credentials.
  </Card>

  <Card title="404 - Not Found" icon="file-slash">
    Resource doesn't exist or URL is incorrect. Check the endpoint path and resource ID.
  </Card>

  <Card title="422 - Unprocessable Entity" icon="file-circle-xmark">
    Request body doesn't match expected model. Missing required fields or wrong data types.
  </Card>

  <Card title="429 - Rate Limit" icon="gauge-high">
    Too many requests. Check rate limit headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`.
  </Card>

  <Card title="5xx - Server Error" icon="server">
    Unexpected server problem. Our team typically fixes these issues quickly. Check status page.
  </Card>
</CardGroup>

## Specific Error Codes

<AccordionGroup>
  <Accordion title="Authentication Errors">
    * **`invalid_api_key`** - The API key in the authorization header is missing, invalid, or has expired. See [authentication](/en/api-reference/authentication) for details.
  </Accordion>

  <Accordion title="Request Format Errors">
    * **`bad_request`** - The request could not be parsed
    * **`invalid_json`** - The request is not valid JSON
    * **`empty_request`** - Request body is empty; ensure you're sending data
    * **`request_canceled`** - The caller canceled the request
    * **`invalid_operation`** - The operation is not valid in the current state
  </Accordion>

  <Accordion title="Auction Errors">
    * **`missing_auctions`** - You must specify at least one auction
    * **`too_many_auctions`** - At most 5 auctions can be run in parallel
    * **`too_few_slots`** - At least one slot must be specified in an auction
    * **`missing_slots`** - Missing required slots field
    * **`invalid_auction_id`** - Auction ID doesn't correspond to a valid auction
    * **`missing_promotion_type`** - Must request slots for at least one promotion type
    * **`invalid_promotion_type`** - Invalid promotion types in slots field
  </Accordion>

  <Accordion title="Context & Placement Errors">
    * **`invalid_context`** - Invalid context. Must specify at most two of: list of products, search query, or categories (for sponsored brands: at most one)
    * **`invalid_placement_id`** - Placement ID must be between 1 and 8
    * **`missing_slot_id`** - Missing required slot ID for banner ads
  </Accordion>

  <Accordion title="Category Errors">
    * **`invalid_category`** - Only one of `id`, `ids`, or `disjunctions` must be set, where no array is longer than 5
  </Accordion>

  <Accordion title="Session Errors">
    * **`invalid_opaque_user_id`** - Opaque user ID value must be no longer than 90 characters
  </Accordion>

  <Accordion title="Product & Catalog Errors">
    * **`no_products`** - At least one product must be specified
    * **`no_products_or_category`** - Either at least one product ID or a category ID must be provided
    * **`too_many_products`** - Exceeded limit of products in the request
    * **`product_info_mismatch`** - Product info arrays must all have the same length
    * **`invalid_quality_score`** - Quality scores must be between 0.0 and 1.0
    * **`non_positive_price`** - Product price must be positive
  </Accordion>

  <Accordion title="Geo Targeting Errors">
    * **`invalid_geo_targeting`** - Invalid geo targeting. Must specify either `location` or `locations`
    * **`too_many_locations`** - At most 2 locations can be specified
    * **`invalid_location_cell`** - Specified location cell is not a valid H3 cell
  </Accordion>

  <Accordion title="Device Errors">
    * **`invalid_device`** - The device must be one of: `desktop` or `mobile`
  </Accordion>

  <Accordion title="Search Errors">
    * **`too_many_search_query_words`** - Exceeded limit of search query words in the request
  </Accordion>

  <Accordion title="Event Tracking Errors">
    * **`invalid_event_time`** - At least one event is in the future
    * **`invalid_resolved_bid_id`** - Invalid resolvedBidId
    * **`invalid_use_of_external_campaign_id`** - Cannot set both `resolvedBidId` and `externalCampaignId`
  </Accordion>

  <Accordion title="Purchase Event Errors">
    * **`no_purchase_items`** - At least one item must be purchased
    * **`missing_purchased_at`** - Required `purchasedAt` field is missing
  </Accordion>

  <Accordion title="Marketplace & Vendor Errors">
    * **`invalid_marketplace`** - No such marketplace exists
    * **`invalid_vendor`** - No such vendor exists
    * **`resource_not_found`** - The requested resource was not found
  </Accordion>

  <Accordion title="Experiment Errors">
    * **`experiment_variant_too_long`** - Marketplace experiment variants have a maximum length of 10 characters
  </Accordion>

  <Accordion title="Ledger & Account Errors">
    * **`account_unique_violation`** - Request breaks ledger account unique constraint
    * **`invalid_ledger_account`** - Ledger account does not exist
    * **`insufficient_balance`** - Insufficient balance
    * **`different_currencies`** - Both accounts must have the same currency code
    * **`equal_from_and_to`** - From and to must be different
  </Accordion>

  <Accordion title="Filter Errors">
    * **`bad_request`** (filter operation) - The filter operation can be one of `and` or `or`
    * **`bad_request`** (attributes) - The number of filter attributes needs to be between 1 and 3
    * **`bad_request`** (promotions) - The number of filter promotions needs to be between 1 and 3
  </Accordion>

  <Accordion title="Travel API Errors">
    * **`invalid_travel_category`** - Travel category must be a non-empty string if provided
    * **`invalid_travel_date_range`** - End date must be greater than start date
    * **`too_many_passengers`** - Number of passengers must be less than ten
    * **`invalid_traveler_type`** - Traveler type must be one of: `family`, `group`, `solo`, `couple`
    * **`invalid_date_format`** - Date must follow format `YYYY-MM-DD` (e.g., 2012-05-08)
    * **`invalid_travel_type`** - Type must be one of: `hotels`, `flights`
    * **`missing_variation_id`** - Missing variation ID
    * **`missing_flight_travel_context`** - Missing fields from flight travel context
  </Accordion>

  <Accordion title="Server Errors">
    * **`internal_server_error`** - The server has encountered a problem
    * **`request_canceled`** - The caller canceled the request
  </Accordion>
</AccordionGroup>

## Common Integration Issues

<CardGroup cols={2}>
  <Card title="Events Not Appearing" icon="eye-slash">
    **Events return 200 but don't show in dashboard:**

    * Check `occurredAt` is within last 30 days
    * Verify product exists in catalog
    * Confirm event type spelling (`click`, not `Click`)
  </Card>

  <Card title="Empty Auction Results" icon="rectangle-xmark">
    **Auctions returning no winners:**

    * **Check campaign budget** (most common issue)
    * **Verify account balance is positive**
    * Confirm products are in stock and active
    * Verify active campaigns exist
    * Check bid amounts aren't too low
  </Card>

  <Card title="Attribution Issues" icon="link-slash">
    **Attribution not working correctly:**

    * See our [Attribution Troubleshooting Guide](/knowledge-base/ad-platform/reporting/attribution-troubleshooting)
    * Check resolved bid IDs are passed correctly
    * Verify purchase events include proper product IDs
  </Card>

  <Card title="Connection Problems" icon="wifi-slash">
    **Connection refused or timeout:**

    * Test connectivity: `curl -I https://api.topsort.com`
    * Check firewall allows outbound HTTPS (port 443)
    * Whitelist `*.topsort.com` domains
    * Verify TLS/SSL certificate validation
  </Card>
</CardGroup>

<Warning>
  **Budget exhaustion is the #1 cause of empty auctions.** Before debugging complex auction issues, first check that your campaigns have sufficient daily budget and account balance. Campaigns with zero budget cannot participate in auctions.
</Warning>

## Detailed Validation Errors

Some endpoints return detailed validation errors with field-level information:

```json theme={null}
{
  "error": "validation_error",
  "message": "Invalid request body",
  "details": [
    {
      "field": "events[0].productId",
      "message": "Product 'sku_999' not found in catalog"
    },
    {
      "field": "events[0].occurredAt",
      "message": "Timestamp cannot be in the future"
    }
  ]
}
```

Use the `details` array to identify exactly which fields have issues and what needs to be corrected.

## Rate Limiting

<CardGroup cols={2}>
  <Card title="Exponential Backoff" icon="arrows-rotate">
    Retry failed requests with increasing delays between attempts:

    ```python theme={null}
    def retry_with_backoff(url, max_retries=5):
        delay = 1
        for i in range(max_retries):
            response = requests.get(url)
            if response.status_code != 429:
                return response
            time.sleep(delay)
            delay = min(delay * 2, 64)
    ```
  </Card>

  <Card title="Use Rate Limit Headers" icon="gauge">
    Respect the rate limit headers in responses:

    * `X-RateLimit-Limit` - Total requests allowed
    * `X-RateLimit-Remaining` - Requests remaining
    * `X-RateLimit-Reset` - When limit resets

    Wait until `X-RateLimit-Reset` before retrying.
  </Card>
</CardGroup>

<Note>
  Auctions (`/v2/auctions`) and Events (`/v2/events`) endpoints are **not rate-limited**. Rate limits apply to other endpoints like campaign management and reporting APIs.
</Note>

## Connection & Network Issues

### Troubleshooting Checklist

<Steps>
  <Step title="Test Basic Connectivity">
    Verify you can reach Topsort's API:

    ```bash theme={null}
    curl -I https://api.topsort.com
    ```
  </Step>

  <Step title="Check Firewall Rules">
    Ensure outbound HTTPS (port 443) traffic is allowed and whitelist:

    * `api.topsort.com`
    * `*.topsort.com`
  </Step>

  <Step title="Verify TLS Support">
    Ensure your HTTP client supports modern TLS versions:

    ```bash theme={null}
    openssl s_client -connect api.topsort.com:443
    ```
  </Step>

  <Step title="Configure Timeouts">
    Set appropriate timeout values and implement retry logic:

    ```python theme={null}
    session = requests.Session()
    session.timeout = (10, 30)  # (connect, read)
    ```
  </Step>

  <Step title="Check Status Page">
    Visit [topsort.statuspage.io](https://topsort.statuspage.io) for service status
  </Step>
</Steps>

### Common Network Issues

<AccordionGroup>
  <Accordion title="SSL/TLS Certificate Problems">
    **Symptoms:** Certificate validation errors, SSL handshake failures

    **Solutions:**

    * Update your HTTP client to support modern TLS versions
    * Ensure your system trusts standard certificate authorities
    * Test with: `openssl s_client -connect api.topsort.com:443`
  </Accordion>

  <Accordion title="Firewall/Proxy Issues">
    **Symptoms:** Connection refused, requests hanging

    **Solutions:**

    * Whitelist Topsort domains (`api.topsort.com`, `*.topsort.com`)
    * Allow outbound HTTPS traffic on port 443
    * Configure proxy settings if required by your network
    * Test without proxy to isolate issue
  </Accordion>

  <Accordion title="Timeout Issues">
    **Symptoms:** Requests timing out, hanging indefinitely

    **Solutions:**

    * Increase timeout values in your HTTP client
    * Implement retry logic with exponential backoff
    * Check for large request payloads exceeding limits
    * Use connection pooling for better performance
  </Accordion>

  <Accordion title="Regional Connectivity">
    **Symptoms:** Issues from specific geographic regions

    **Solutions:**

    * Test from different locations to isolate regional problems
    * Use a CDN or proxy service if needed
    * Contact support with your location details
  </Accordion>
</AccordionGroup>

## Debugging Tools

<CardGroup cols={2}>
  <Card title="Developer Logs" icon="list-check">
    Check the **Dev Tools** tab in your Ad Platform for detailed API request/response logs.

    See our [Developer Logs guide](/api-reference/logs) for help interpreting log entries.
  </Card>

  <Card title="Status Page" icon="signal">
    Monitor service health and planned maintenance at [topsort.statuspage.io](https://topsort.statuspage.io)

    Subscribe to updates for real-time notifications.
  </Card>
</CardGroup>

## Need Help?

If you're still experiencing issues after consulting this guide:

* **Check status page:** [topsort.statuspage.io](https://topsort.statuspage.io)
* **Contact support** with error details and API request examples
* **Review API docs** for endpoint-specific requirements
