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
| Code | Status | Description |
|---|---|---|
| 200 | OK | Request succeeded |
| 201 | Created | Resource created |
| 204 | No Content | Request succeeded, no response body |
Client Error Codes
| Code | Status | Description |
|---|---|---|
| 400 | Bad Request | Invalid request syntax or parameters |
| 401 | Unauthorized | Missing or invalid API key |
| 402 | Payment Required | Insufficient budget |
| 403 | Forbidden | API key lacks permission |
| 404 | Not Found | Resource doesn’t exist |
| 409 | Conflict | Resource conflict (e.g., name taken) |
| 413 | Payload Too Large | Request body too large |
| 422 | Unprocessable Entity | Valid syntax but invalid semantics |
| 429 | Too Many Requests | Rate limit exceeded |
Server Error Codes
| Code | Status | Description |
|---|---|---|
| 500 | Internal Server Error | Server error |
| 502 | Bad Gateway | Upstream service error |
| 503 | Service Unavailable | Temporary outage |
| 504 | Gateway Timeout | Request 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
Authorizationheader 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
retryAfterseconds - 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
| Code | Description |
|---|---|
VALIDATION_FAILED | Request body validation failed |
INSUFFICIENT_BUDGET | Not enough budget balance |
DAILY_LIMIT_EXCEEDED | Daily spending limit reached |
MONTHLY_LIMIT_EXCEEDED | Monthly spending limit reached |
EXECUTION_TIMEOUT | Task exceeded time limit |
EXECUTION_FAILED | Agent execution error |
RATE_LIMITED | Too many requests |
INTERNAL_ERROR | Server-side error |
Debugging Tips
Include Request ID
Responses include an x-request-id header:
x-request-id: req_abc123def456Include this when contacting support.
Check Response Headers
Useful debugging headers:
| Header | Description |
|---|---|
x-request-id | Unique request identifier |
x-ratelimit-limit | Rate limit ceiling |
x-ratelimit-remaining | Remaining requests |
retry-after | Seconds 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();
}
}Related
- Authentication - API key setup
- Billing - Budget management
- API Overview - Getting started
Last updated on