MarketIntell

Error Handling

Error formats, common error codes, and retry strategies

Error Handling

All MarketIntell API errors follow a consistent format. This guide covers error responses, common error codes, rate limit handling, and retry strategies.

Error Response Format

Every error response has the same structure:

{
  "success": false,
  "error": "Human-readable error description"
}

The HTTP status code indicates the error category, and the error field provides specific details.

Common Error Codes

Status CodeMeaningCommon Causes
400Bad RequestInvalid JSON, missing required fields, invalid parameter values
401UnauthorizedMissing or invalid API key
403ForbiddenAPI key lacks required scope for this endpoint
404Not FoundResource doesn't exist (session, portfolio, agent, etc.)
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer-side error — retry after a delay

400 — Bad Request

{
  "success": false,
  "error": "Validation error: 'message' is required"
}

Fix: Check your request body against the API reference. Ensure all required fields are present and correctly typed.

401 — Unauthorized

{
  "success": false,
  "error": "Invalid or missing API key"
}

Fix: Verify that you're sending the X-API-Key header with a valid key.

403 — Forbidden

{
  "success": false,
  "error": "API key does not have 'portfolio' scope"
}

Fix: Create a new API key with the required scope, or update the existing key's scopes via PATCH /v1/auth/keys/:id.

429 — Rate Limit Exceeded

{
  "success": false,
  "error": "Rate limit exceeded. Resets at 2025-01-16T00:00:00Z"
}

Fix: Wait until the reset time, or upgrade your plan for higher limits.

500 — Internal Server Error

{
  "success": false,
  "error": "An unexpected error occurred. Please try again."
}

Fix: Retry with exponential backoff. If the error persists, contact support.

Rate Limit Handling

Every response includes rate limit headers:

X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705363200

Proactive Rate Limit Handling

Check remaining quota before making requests:

async function chatWithRateLimitCheck(message: string, apiKey: string) {
  const response = await fetch("https://api.marketintell.ai/v1/chat", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": apiKey,
    },
    body: JSON.stringify({ message }),
  });

  // Track rate limits
  const remaining = parseInt(response.headers.get("X-RateLimit-Remaining") || "0");
  const resetAt = parseInt(response.headers.get("X-RateLimit-Reset") || "0");

  if (remaining < 5) {
    console.warn(`Low quota: ${remaining} requests remaining. Resets at ${new Date(resetAt * 1000).toISOString()}`);
  }

  if (response.status === 429) {
    const waitMs = (resetAt * 1000) - Date.now();
    console.log(`Rate limited. Waiting ${Math.ceil(waitMs / 1000)}s...`);
    await new Promise(resolve => setTimeout(resolve, waitMs));
    return chatWithRateLimitCheck(message, apiKey); // Retry
  }

  return response.json();
}

Retry Strategies

Exponential Backoff

For 429 and 500 errors, use exponential backoff with jitter:

async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3
): Promise<Response> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, options);

    // Don't retry client errors (except 429)
    if (response.ok || (response.status >= 400 && response.status < 500 && response.status !== 429)) {
      return response;
    }

    if (attempt === maxRetries) {
      return response; // Return last response after all retries
    }

    // Exponential backoff with jitter
    const baseDelay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
    const jitter = Math.random() * 1000;
    const delay = baseDelay + jitter;

    console.log(`Retry ${attempt + 1}/${maxRetries} in ${Math.round(delay)}ms...`);
    await new Promise(resolve => setTimeout(resolve, delay));
  }

  throw new Error("Unreachable");
}

Python Retry

import time
import random
import requests

def fetch_with_retry(url, headers, json_body, max_retries=3):
    for attempt in range(max_retries + 1):
        response = requests.post(url, headers=headers, json=json_body)

        if response.ok:
            return response.json()

        if response.status_code in (429, 500, 502, 503):
            if attempt == max_retries:
                response.raise_for_status()

            base_delay = (2 ** attempt)
            jitter = random.uniform(0, 1)
            delay = base_delay + jitter

            print(f"Retry {attempt + 1}/{max_retries} in {delay:.1f}s...")
            time.sleep(delay)
            continue

        # Non-retryable error
        response.raise_for_status()

What to Retry

ErrorRetry?Strategy
400 Bad RequestNoFix the request
401 UnauthorizedNoFix authentication
403 ForbiddenNoUpdate API key scopes
404 Not FoundNoCheck resource ID
429 Rate LimitedYesWait for X-RateLimit-Reset
500 Server ErrorYesExponential backoff
502 Bad GatewayYesExponential backoff
503 Service UnavailableYesExponential backoff
Connection timeoutYesExponential backoff

On this page