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

# Error Handling

> Understanding and handling API errors

The Claro API uses standard HTTP status codes and returns detailed error information in JSON format to help you diagnose and handle errors effectively.

## Error Response Format

All error responses follow a consistent structure:

```json theme={null}
{
  "error": {
    "code": "error_code",
    "message": "Human-readable error message",
    "details": {
      // Optional additional context
    }
  }
}
```

## HTTP Status Codes

The API uses standard HTTP status codes to indicate success or failure:

| Status Code | Meaning               | Common Causes                |
| ----------- | --------------------- | ---------------------------- |
| **200**     | OK                    | Request succeeded            |
| **400**     | Bad Request           | Invalid request parameters   |
| **401**     | Unauthorized          | Missing or invalid API key   |
| **403**     | Forbidden             | Insufficient permissions     |
| **404**     | Not Found             | Resource doesn't exist       |
| **429**     | Too Many Requests     | Rate limit exceeded          |
| **500**     | Internal Server Error | Server-side error            |
| **503**     | Service Unavailable   | Temporary service disruption |

## Common Error Codes

### Authentication Errors

#### 401 Unauthorized

**Error Code:** `unauthorized`

The API key is missing or invalid.

```json theme={null}
{
  "error": {
    "code": "unauthorized",
    "message": "Invalid API key"
  }
}
```

**Solutions:**

* Verify your API key is correct
* Check that you're using the `Bearer` prefix in the Authorization header
* Ensure the key hasn't been deleted from your account
* Get a new API key from [claro.baytos.ai](https://claro.baytos.ai)

#### 403 Forbidden

**Error Code:** `forbidden`

Your API key is valid but lacks permission to access the resource.

```json theme={null}
{
  "error": {
    "code": "forbidden",
    "message": "You don't have access to this workspace"
  }
}
```

**Solutions:**

* Verify you're a member of the workspace
* Check that the prompt exists and is accessible to you
* Ensure your workspace subscription is active

### Resource Errors

#### 404 Not Found

**Error Code:** `not_found`

The requested resource doesn't exist.

```json theme={null}
{
  "error": {
    "code": "not_found",
    "message": "Prompt not found: @workspace/nonexistent:v1"
  }
}
```

**Solutions:**

* Verify the package name is spelled correctly
* Check that the version exists (e.g., `:v1`, `:v2`)
* Ensure you have access to the workspace

### Validation Errors

#### 400 Bad Request

**Error Code:** `validation_error`

The request contains invalid parameters.

```json theme={null}
{
  "error": {
    "code": "validation_error",
    "message": "Invalid package name format",
    "details": {
      "field": "prompt_id",
      "expected": "@namespace/prompt-name:version"
    }
  }
}
```

**Solutions:**

* Check the request parameters match the expected format
* Review the API documentation for the endpoint
* Ensure all required fields are provided

### Rate Limiting Errors

#### 429 Too Many Requests

**Error Code:** `rate_limit_exceeded`

You've exceeded the rate limit.

```json theme={null}
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "retry_after": 60
  }
}
```

**Solutions:**

* Wait for the duration specified in `retry_after`
* Implement exponential backoff retry logic
* Reduce request frequency
* Contact support for higher rate limits

See [Rate Limits](/api-reference/rate-limits) for detailed guidance.

### Server Errors

#### 500 Internal Server Error

**Error Code:** `internal_error`

An unexpected error occurred on the server.

```json theme={null}
{
  "error": {
    "code": "internal_error",
    "message": "An unexpected error occurred. Please try again later."
  }
}
```

**Solutions:**

* Retry the request after a short delay
* Check [status.baytos.ai](https://status.baytos.ai) for service status
* Contact support if the issue persists

#### 503 Service Unavailable

**Error Code:** `service_unavailable`

The service is temporarily unavailable.

```json theme={null}
{
  "error": {
    "code": "service_unavailable",
    "message": "Service temporarily unavailable. Please try again later."
  }
}
```

**Solutions:**

* Wait a few moments and retry
* Implement exponential backoff
* Check service status page

## Error Handling Examples

### Python SDK

The SDK provides specific exception types for different errors:

```python theme={null}
from baytos.claro import (
    BaytClient,
    BaytAuthError,
    BaytNotFoundError,
    BaytRateLimitError,
    BaytAPIError
)

client = BaytClient(api_key="your_api_key")

try:
    prompt = client.get_prompt("@workspace/my-prompt:v1")
    print(f"Successfully loaded: {prompt.title}")

except BaytNotFoundError as e:
    print(f"Prompt not found: {e}")
    # Handle missing prompt - maybe use a fallback

except BaytAuthError as e:
    print(f"Authentication failed: {e}")
    # Check API key configuration

except BaytRateLimitError as e:
    print(f"Rate limit exceeded: {e}")
    # Wait and retry, or queue for later

except BaytAPIError as e:
    print(f"API error occurred: {e}")
    # Log error and notify administrators

except Exception as e:
    print(f"Unexpected error: {e}")
    # Handle any other errors
```

### Python with requests

```python theme={null}
import requests
import time

def get_prompt(package_name, api_key, max_retries=3):
    url = f"https://api.baytos.ai/v1/prompts/{package_name}"
    headers = {"Authorization": f"Bearer {api_key}"}

    for attempt in range(max_retries):
        try:
            response = requests.get(url, headers=headers)

            if response.status_code == 200:
                return response.json()

            elif response.status_code == 401:
                raise Exception("Invalid API key")

            elif response.status_code == 403:
                raise Exception("Access denied")

            elif response.status_code == 404:
                raise Exception(f"Prompt not found: {package_name}")

            elif response.status_code == 429:
                if attempt < max_retries - 1:
                    retry_after = int(response.headers.get('Retry-After', 60))
                    time.sleep(retry_after)
                    continue
                else:
                    raise Exception("Rate limit exceeded")

            elif response.status_code >= 500:
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)  # Exponential backoff
                    continue
                else:
                    raise Exception("Server error")

            else:
                response.raise_for_status()

        except requests.exceptions.RequestException as e:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)
                continue
            raise

    raise Exception("Max retries exceeded")
```

### JavaScript with fetch

```javascript theme={null}
async function getPrompt(packageName, apiKey, maxRetries = 3) {
  const url = `https://api.baytos.ai/v1/prompts/${packageName}`;
  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  };

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, { headers });

      if (response.ok) {
        return await response.json();
      }

      const error = await response.json();

      switch (response.status) {
        case 401:
          throw new Error(`Authentication failed: ${error.error.message}`);

        case 403:
          throw new Error(`Access denied: ${error.error.message}`);

        case 404:
          throw new Error(`Prompt not found: ${packageName}`);

        case 429:
          if (attempt < maxRetries - 1) {
            const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
            console.log(`Rate limited. Retrying after ${retryAfter}s...`);
            await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
            continue;
          }
          throw new Error('Rate limit exceeded');

        case 500:
        case 503:
          if (attempt < maxRetries - 1) {
            const delay = Math.pow(2, attempt) * 1000;
            await new Promise(resolve => setTimeout(resolve, delay));
            continue;
          }
          throw new Error(`Server error: ${error.error.message}`);

        default:
          throw new Error(`HTTP ${response.status}: ${error.error.message}`);
      }
    } catch (err) {
      if (attempt === maxRetries - 1) throw err;
    }
  }

  throw new Error('Max retries exceeded');
}

// Usage
try {
  const prompt = await getPrompt('@workspace/my-prompt:v1', apiKey);
  console.log(prompt);
} catch (error) {
  console.error('Failed to fetch prompt:', error.message);
}
```

## Troubleshooting Guide

<AccordionGroup>
  <Accordion title="Invalid API key errors">
    **Symptoms:** 401 Unauthorized responses

    **Checklist:**

    * [ ] API key is correctly copied (no extra spaces)
    * [ ] Environment variable is set correctly
    * [ ] Using `Bearer` prefix in Authorization header
    * [ ] API key hasn't been deleted
    * [ ] Testing with the correct API endpoint

    **Solution:** Create a new API key and update your configuration.
  </Accordion>

  <Accordion title="Prompt not found errors">
    **Symptoms:** 404 Not Found responses

    **Checklist:**

    * [ ] Package name format is correct: `@namespace/prompt-name:version`
    * [ ] The prompt exists in your workspace
    * [ ] You have access to the workspace
    * [ ] The version number is correct (e.g., `:v1` not `:1`)

    **Solution:** Verify the package name in the Claro dashboard.
  </Accordion>

  <Accordion title="Intermittent failures">
    **Symptoms:** Requests sometimes fail with 500 or timeout errors

    **Checklist:**

    * [ ] Implement retry logic with exponential backoff
    * [ ] Add timeout to requests (30s recommended)
    * [ ] Check network connectivity
    * [ ] Monitor API status page

    **Solution:** Implement robust retry logic and error handling.
  </Accordion>

  <Accordion title="Rate limit errors">
    **Symptoms:** 429 Too Many Requests responses

    **Checklist:**

    * [ ] Implement exponential backoff
    * [ ] Respect `Retry-After` header
    * [ ] Cache responses when possible
    * [ ] Batch requests efficiently

    **Solution:** See [Rate Limits](/api-reference/rate-limits) guide.
  </Accordion>
</AccordionGroup>

## Error Logging Best Practices

Log errors with sufficient context for debugging:

```python theme={null}
import logging

logger = logging.getLogger(__name__)

try:
    prompt = client.get_prompt(package_name)
except BaytAPIError as e:
    logger.error(
        "Failed to fetch prompt",
        extra={
            "package_name": package_name,
            "error_code": e.code,
            "error_message": str(e),
            "user_id": user_id,
            "request_id": request_id
        }
    )
    raise
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Rate Limits" icon="gauge" href="/api-reference/rate-limits">
    Learn about rate limiting and retry strategies
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Understand API authentication
  </Card>

  <Card title="Python SDK" icon="python" href="/sdk/python/error-handling">
    SDK error handling patterns
  </Card>

  <Card title="Examples" icon="code" href="/examples/error-handling">
    See error handling code examples
  </Card>
</CardGroup>
