Skip to Content
APIError Handling

Error Handling

The Computer Agents API uses conventional HTTP status codes and returns detailed error information to help you handle errors gracefully.

Error Response Format

All errors return a JSON object with error and message fields:

{ "error": "Not Found", "message": "Thread thread_xyz123 not found" }

Extended Error Response

Some errors include additional context:

{ "error": "Validation Error", "message": "Invalid request body", "code": "VALIDATION_FAILED", "details": [ { "field": "content", "message": "content is required" }, { "field": "title", "message": "title must be a string" } ] }

HTTP Status Codes

Success Codes

CodeStatusDescription
200OKRequest succeeded
201CreatedResource created
204No ContentRequest succeeded, no response body

Client Error Codes

CodeStatusDescription
400Bad RequestInvalid request syntax or parameters
401UnauthorizedMissing or invalid API key
402Payment RequiredInsufficient budget
403ForbiddenAPI key lacks permission
404Not FoundResource doesn’t exist
409ConflictResource conflict (e.g., name taken)
413Payload Too LargeRequest body too large
422Unprocessable EntityValid syntax but invalid semantics
429Too Many RequestsRate limit exceeded

Server Error Codes

CodeStatusDescription
500Internal Server ErrorServer error
502Bad GatewayUpstream service error
503Service UnavailableTemporary outage
504Gateway TimeoutRequest timeout

Common Errors

401 Unauthorized

Missing or invalid API key.

{ "error": "Unauthorized", "message": "Invalid or missing API key" }

Solutions:

  • Verify the API key is correct
  • Check the Authorization header format: Bearer {key}
  • Ensure the key hasn’t been revoked

402 Payment Required

Insufficient budget for the operation.

{ "error": "Payment Required", "message": "Insufficient budget to execute", "code": "INSUFFICIENT_BUDGET", "budgetStatus": { "balance": 0.30, "dailyLimit": 10.00, "dailySpent": 9.80, "monthlyLimit": 100.00, "monthlySpent": 85.00 } }

Solutions:

  • Add funds to your account
  • Check budget status before executing
  • Adjust daily/monthly limits
  • Set up budget alerts

404 Not Found

Resource doesn’t exist.

{ "error": "Not Found", "message": "Thread thread_xyz123 not found" }

Solutions:

  • Verify the resource ID is correct
  • Check if the resource was deleted
  • Ensure you have access to the resource

409 Conflict

Resource conflict, typically name collisions or state conflicts.

{ "error": "Conflict", "message": "Thread is already processing" }

Solutions:

  • Wait for the current operation to complete
  • Use a different name
  • Cancel the existing operation first

429 Too Many Requests

Rate limit exceeded.

{ "error": "Too Many Requests", "message": "Rate limit exceeded", "retryAfter": 60 }

Solutions:

  • Wait and retry after retryAfter seconds
  • Implement exponential backoff
  • Reduce request frequency

Error Handling Best Practices

JavaScript/TypeScript

async function createThread(data: object) { const response = await fetch( 'https://api.computer-agents.com/v1/threads', { method: 'POST', headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) } ); if (!response.ok) { const error = await response.json(); switch (response.status) { case 401: throw new Error('Invalid API key'); case 402: throw new Error(`Insufficient budget: $${error.budgetStatus?.balance}`); case 404: throw new Error('Resource not found'); case 429: // Retry after delay const retryAfter = error.retryAfter || 60; await sleep(retryAfter * 1000); return createThread(data); default: throw new Error(error.message || 'Unknown error'); } } return response.json(); }

Python

import requests import time def create_thread(data: dict): response = requests.post( 'https://api.computer-agents.com/v1/threads', headers={ 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' }, json=data ) if response.status_code == 401: raise AuthenticationError('Invalid API key') if response.status_code == 402: error = response.json() raise InsufficientBudgetError( f"Balance: ${error.get('budgetStatus', {}).get('balance')}" ) if response.status_code == 404: raise NotFoundError('Resource not found') if response.status_code == 429: error = response.json() retry_after = error.get('retryAfter', 60) time.sleep(retry_after) return create_thread(data) response.raise_for_status() return response.json()

Retry Strategy

Implement exponential backoff for transient errors:

async function fetchWithRetry( url: string, options: RequestInit, maxRetries = 3 ): Promise<Response> { let lastError: Error | null = null; for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await fetch(url, options); // Don't retry client errors (except 429) if (response.status >= 400 && response.status < 500 && response.status !== 429) { return response; } // Retry on 429 or 5xx if (response.status === 429 || response.status >= 500) { const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s await sleep(delay); continue; } return response; } catch (error) { lastError = error as Error; const delay = Math.pow(2, attempt) * 1000; await sleep(delay); } } throw lastError || new Error('Max retries exceeded'); }

Error Codes Reference

CodeDescription
VALIDATION_FAILEDRequest body validation failed
INSUFFICIENT_BUDGETNot enough budget balance
DAILY_LIMIT_EXCEEDEDDaily spending limit reached
MONTHLY_LIMIT_EXCEEDEDMonthly spending limit reached
EXECUTION_TIMEOUTTask exceeded time limit
EXECUTION_FAILEDAgent execution error
RATE_LIMITEDToo many requests
INTERNAL_ERRORServer-side error

Debugging Tips

Include Request ID

Responses include an x-request-id header:

x-request-id: req_abc123def456

Include this when contacting support.

Check Response Headers

Useful debugging headers:

HeaderDescription
x-request-idUnique request identifier
x-ratelimit-limitRate limit ceiling
x-ratelimit-remainingRemaining requests
retry-afterSeconds to wait (on 429)

Handling Budget Errors

The 402 error includes detailed budget information:

if (response.status === 402) { const { budgetStatus } = await response.json(); if (budgetStatus.balance < 1) { // No balance - prompt to add funds showAddCreditsPrompt(); } else if (budgetStatus.dailySpent >= budgetStatus.dailyLimit) { // Hit daily limit showDailyLimitReachedMessage(); } else if (budgetStatus.monthlySpent >= budgetStatus.monthlyLimit) { // Hit monthly limit showMonthlyLimitReachedMessage(); } }

Last updated on