Skip to main content

PolyhushAPIError

All SDK methods raise PolyhushAPIError when an API request fails. This exception provides detailed information about what went wrong.
from polyhush import PolyhushClient, PolyhushAPIError

client = PolyhushClient(api_key="your-api-key")

try:
    result = client.buy(token_id="...", shares=10, price=0.5)
except PolyhushAPIError as e:
    print(f"Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    print(f"Response: {e.response}")

Exception Properties

message
string
Human-readable error message describing what went wrong.
status_code
integer
HTTP status code from the API response (e.g., 400, 401, 404, 500).
response
dict
Full error response from the API, which may contain additional details.

Common Error Codes

Status CodeMeaningCommon Causes
400Bad RequestInvalid parameters, insufficient balance
401UnauthorizedInvalid or missing API key
403ForbiddenAction not permitted
404Not FoundOrder/market doesn’t exist
422Validation ErrorInvalid input data
429Rate LimitedToo many requests
500Server ErrorInternal API error

Error Handling Patterns

Basic Try/Catch

from polyhush import PolyhushClient, PolyhushAPIError

client = PolyhushClient(api_key="your-api-key")

try:
    result = client.buy(
        token_id="your-token-id",
        shares=10,
        price=0.55
    )
    print(f"Order placed: {result['order_id']}")
except PolyhushAPIError as e:
    print(f"Failed to place order: {e.message}")

Handling Specific Errors

from polyhush import PolyhushAPIError

try:
    result = client.buy(token_id=token_id, shares=100, price=0.50)
except PolyhushAPIError as e:
    if e.status_code == 400:
        # Bad request - check balance or parameters
        print(f"Invalid request: {e.message}")
    elif e.status_code == 401:
        # Authentication issue
        print("Check your API key")
    elif e.status_code == 429:
        # Rate limited
        print("Too many requests, slow down")
        time.sleep(60)
    else:
        # Unknown error
        print(f"Unexpected error ({e.status_code}): {e.message}")

Retry Logic with Exponential Backoff

import time
from polyhush import PolyhushAPIError

def place_order_with_retry(client, token_id, shares, price, max_retries=3):
    """Place an order with automatic retry on transient failures."""
    
    for attempt in range(max_retries):
        try:
            return client.buy(
                token_id=token_id,
                shares=shares,
                price=price
            )
        except PolyhushAPIError as e:
            # Don't retry client errors (4xx except 429)
            if 400 <= e.status_code < 500 and e.status_code != 429:
                raise
            
            # Retry on server errors (5xx) and rate limits (429)
            if attempt < max_retries - 1:
                wait_time = (2 ** attempt) + random.uniform(0, 1)
                print(f"Retrying in {wait_time:.1f}s...")
                time.sleep(wait_time)
            else:
                raise

Validating Before Trading

from polyhush import PolyhushAPIError

def safe_buy(client, token_id, shares, price):
    """Buy with pre-validation."""
    
    # Check balance first
    try:
        balance = client.get_balance()
        required = shares * price
        
        if balance['available_balance'] < required:
            print(f"Insufficient balance: need ${required:.2f}, have ${balance['available_balance']:.2f}")
            return None
            
    except PolyhushAPIError as e:
        print(f"Could not check balance: {e.message}")
        return None
    
    # Place the order
    try:
        return client.buy(token_id=token_id, shares=shares, price=price)
    except PolyhushAPIError as e:
        print(f"Order failed: {e.message}")
        return None

Common Error Scenarios

try:
    client.buy(token_id=token_id, shares=1000, price=0.50)
except PolyhushAPIError as e:
    if "insufficient" in e.message.lower():
        balance = client.get_balance()
        print(f"Need more funds. Available: ${balance['available_balance']:.2f}")
try:
    client.buy(token_id="invalid-token", shares=10, price=0.50)
except PolyhushAPIError as e:
    if e.status_code == 404:
        print("Token not found - check the token ID")
try:
    client.cancel_order(order_id=order_id)
except PolyhushAPIError as e:
    if "already" in e.message.lower():
        print("Order was already cancelled or filled")
import time

try:
    for token in tokens:
        client.get_ticker(token)
except PolyhushAPIError as e:
    if e.status_code == 429:
        print("Rate limited - waiting 60 seconds")
        time.sleep(60)

Best Practices

Always Catch Errors

Wrap API calls in try/except to handle failures gracefully

Log Error Details

Log the full error response for debugging production issues

Implement Retries

Use exponential backoff for transient failures

Validate First

Check balances and positions before placing orders