# Error Codes Reference

This comprehensive reference covers all BroxiAI error codes, their meanings, and specific solutions for each error type.

## HTTP Status Codes

### Client Error Codes (4xx)

| Code | Status               | Meaning                   | Common Causes                      | Solutions                                  |
| ---- | -------------------- | ------------------------- | ---------------------------------- | ------------------------------------------ |
| 400  | Bad Request          | Invalid request syntax    | Malformed JSON, missing parameters | Check request format and required fields   |
| 401  | Unauthorized         | Authentication failed     | Invalid/missing API token          | Verify API token validity                  |
| 403  | Forbidden            | Access denied             | Insufficient permissions           | Check account permissions and plan limits  |
| 404  | Not Found            | Resource doesn't exist    | Wrong ID, deleted resource         | Verify resource ID and existence           |
| 405  | Method Not Allowed   | HTTP method not supported | Using GET instead of POST          | Check API documentation for correct method |
| 409  | Conflict             | Resource conflict         | Duplicate resource creation        | Check for existing resources               |
| 422  | Unprocessable Entity | Validation failed         | Invalid data format                | Validate input data against schema         |
| 429  | Too Many Requests    | Rate limit exceeded       | Too many API calls                 | Implement rate limiting and backoff        |

### Server Error Codes (5xx)

| Code | Status                | Meaning                  | Common Causes               | Solutions                             |
| ---- | --------------------- | ------------------------ | --------------------------- | ------------------------------------- |
| 500  | Internal Server Error | Server-side issue        | System error, bug           | Contact support with error details    |
| 502  | Bad Gateway           | Upstream service error   | Third-party service down    | Check service status, retry later     |
| 503  | Service Unavailable   | Service temporarily down | Maintenance, overload       | Check status page, retry later        |
| 504  | Gateway Timeout       | Upstream service timeout | Slow response from services | Retry request, check timeout settings |

## BroxiAI-Specific Error Codes

### Authentication Errors

#### AUTH\_TOKEN\_INVALID

```json
{
  "error": "AUTH_TOKEN_INVALID",
  "message": "The provided authentication token is invalid",
  "code": 4001,
  "timestamp": "2024-01-01T12:00:00Z"
}
```

**Causes**:

* Token is malformed or corrupted
* Token has been revoked
* Token is for wrong environment

**Solutions**:

1. Regenerate API token from dashboard
2. Verify token format (should start with `bx_`)
3. Check environment (staging vs production)

#### AUTH\_TOKEN\_EXPIRED

```json
{
  "error": "AUTH_TOKEN_EXPIRED",
  "message": "Authentication token has expired",
  "code": 4002,
  "expired_at": "2024-01-01T10:00:00Z"
}
```

**Solutions**:

1. Generate new API token
2. Implement automatic token refresh
3. Set up expiration alerts

#### AUTH\_INSUFFICIENT\_SCOPE

```json
{
  "error": "AUTH_INSUFFICIENT_SCOPE",
  "message": "Token lacks required permissions",
  "code": 4003,
  "required_scope": "workflows:execute",
  "current_scope": "workflows:read"
}
```

**Solutions**:

1. Regenerate token with required permissions
2. Contact admin for permission upgrade
3. Check account plan limits

### Workflow Errors

#### WORKFLOW\_NOT\_FOUND

```json
{
  "error": "WORKFLOW_NOT_FOUND",
  "message": "The specified workflow does not exist",
  "code": 4041,
  "workflow_id": "flow_abc123"
}
```

**Causes**:

* Workflow was deleted
* Wrong workflow ID
* Workflow not published

**Solutions**:

1. Verify workflow ID
2. Check if workflow is published
3. Ensure workflow exists in current workspace

#### WORKFLOW\_NOT\_PUBLISHED

```json
{
  "error": "WORKFLOW_NOT_PUBLISHED",
  "message": "Workflow must be published before execution",
  "code": 4042,
  "workflow_id": "flow_abc123"
}
```

**Solutions**:

1. Publish workflow from editor
2. Check workflow validation errors
3. Ensure all components are configured

#### WORKFLOW\_EXECUTION\_FAILED

```json
{
  "error": "WORKFLOW_EXECUTION_FAILED",
  "message": "Workflow execution encountered an error",
  "code": 5001,
  "workflow_id": "flow_abc123",
  "execution_id": "exec_xyz789",
  "failed_component": "openai_component",
  "component_error": "API quota exceeded"
}
```

**Solutions**:

1. Check component configuration
2. Review error logs
3. Fix failing component
4. Retry execution

#### WORKFLOW\_TIMEOUT

```json
{
  "error": "WORKFLOW_TIMEOUT",
  "message": "Workflow execution exceeded timeout limit",
  "code": 5002,
  "workflow_id": "flow_abc123",
  "timeout_seconds": 300,
  "elapsed_seconds": 301
}
```

**Solutions**:

1. Optimize workflow performance
2. Increase timeout settings
3. Break down complex workflows
4. Use async processing

### Component Errors

#### COMPONENT\_CONFIGURATION\_ERROR

```json
{
  "error": "COMPONENT_CONFIGURATION_ERROR",
  "message": "Required parameter is missing or invalid",
  "code": 4220,
  "component_id": "comp_123",
  "component_type": "OpenAI Model",
  "missing_parameters": ["api_key"],
  "invalid_parameters": {
    "temperature": "Must be between 0 and 2"
  }
}
```

**Solutions**:

1. Provide all required parameters
2. Validate parameter values
3. Check parameter format
4. Review component documentation

#### COMPONENT\_CONNECTION\_ERROR

```json
{
  "error": "COMPONENT_CONNECTION_ERROR",
  "message": "Components cannot be connected due to incompatible data types",
  "code": 4221,
  "source_component": "text_processor",
  "target_component": "number_analyzer",
  "source_output_type": "string",
  "target_input_type": "number"
}
```

**Solutions**:

1. Add data transformation component
2. Check component compatibility
3. Verify data type mappings
4. Review workflow design

#### COMPONENT\_EXECUTION\_ERROR

```json
{
  "error": "COMPONENT_EXECUTION_ERROR",
  "message": "Component failed during execution",
  "code": 5003,
  "component_id": "comp_123",
  "component_type": "File Processor",
  "execution_error": "Unsupported file format: .xyz"
}
```

**Solutions**:

1. Check component inputs
2. Verify supported formats
3. Review component logs
4. Update component configuration

### API Integration Errors

#### API\_KEY\_INVALID

```json
{
  "error": "API_KEY_INVALID",
  "message": "The provided API key for external service is invalid",
  "code": 4031,
  "service": "OpenAI",
  "component_id": "comp_openai_1"
}
```

**Solutions**:

1. Verify API key for external service
2. Check API key permissions
3. Regenerate API key if needed
4. Ensure correct environment (test/prod)

#### API\_QUOTA\_EXCEEDED

```json
{
  "error": "API_QUOTA_EXCEEDED",
  "message": "API quota has been exceeded",
  "code": 4290,
  "service": "OpenAI",
  "quota_type": "tokens",
  "current_usage": 150000,
  "limit": 100000,
  "reset_time": "2024-02-01T00:00:00Z"
}
```

**Solutions**:

1. Wait for quota reset
2. Upgrade API plan
3. Optimize token usage
4. Implement usage monitoring

#### API\_SERVICE\_UNAVAILABLE

```json
{
  "error": "API_SERVICE_UNAVAILABLE",
  "message": "External API service is temporarily unavailable",
  "code": 5030,
  "service": "Google Cloud AI",
  "retry_after": 300
}
```

**Solutions**:

1. Wait and retry after specified time
2. Check service status page
3. Implement retry logic
4. Use alternative service if available

### Data Processing Errors

#### FILE\_TOO\_LARGE

```json
{
  "error": "FILE_TOO_LARGE",
  "message": "File exceeds maximum size limit",
  "code": 4130,
  "file_size": 104857600,
  "max_size": 104857600,
  "filename": "large_document.pdf"
}
```

**Solutions**:

1. Compress file before upload
2. Split large files into smaller chunks
3. Use file compression tools
4. Upgrade plan for larger limits

#### FILE\_FORMAT\_UNSUPPORTED

```json
{
  "error": "FILE_FORMAT_UNSUPPORTED",
  "message": "File format is not supported",
  "code": 4131,
  "filename": "document.xyz",
  "file_extension": ".xyz",
  "supported_formats": [".pdf", ".docx", ".txt"]
}
```

**Solutions**:

1. Convert file to supported format
2. Check supported format list
3. Use file conversion tools
4. Contact support for format requests

#### TEXT\_PROCESSING\_FAILED

```json
{
  "error": "TEXT_PROCESSING_FAILED",
  "message": "Failed to extract or process text from file",
  "code": 5004,
  "filename": "corrupted_file.pdf",
  "processing_error": "Invalid PDF structure"
}
```

**Solutions**:

1. Verify file is not corrupted
2. Try different file format
3. Re-create or re-export file
4. Use OCR for scanned documents

### Memory and State Errors

#### MEMORY\_LIMIT\_EXCEEDED

```json
{
  "error": "MEMORY_LIMIT_EXCEEDED",
  "message": "Workflow memory usage exceeded limit",
  "code": 5005,
  "memory_usage": "2GB",
  "memory_limit": "1GB",
  "component_id": "large_data_processor"
}
```

**Solutions**:

1. Optimize data processing
2. Process data in smaller chunks
3. Clear unnecessary variables
4. Upgrade to higher memory plan

#### SESSION\_EXPIRED

```json
{
  "error": "SESSION_EXPIRED",
  "message": "User session has expired",
  "code": 4014,
  "session_id": "sess_abc123",
  "expired_at": "2024-01-01T12:00:00Z"
}
```

**Solutions**:

1. Re-authenticate user
2. Implement session refresh
3. Check session timeout settings
4. Use persistent authentication

#### STATE\_PERSISTENCE\_FAILED

```json
{
  "error": "STATE_PERSISTENCE_FAILED",
  "message": "Failed to save workflow state",
  "code": 5006,
  "workflow_id": "flow_abc123",
  "storage_error": "Database connection timeout"
}
```

**Solutions**:

1. Retry workflow execution
2. Check storage connectivity
3. Verify storage permissions
4. Contact support if persistent

### Rate Limiting Errors

#### RATE\_LIMIT\_EXCEEDED

```json
{
  "error": "RATE_LIMIT_EXCEEDED",
  "message": "API rate limit exceeded",
  "code": 4290,
  "limit": 1000,
  "window": "hour",
  "current_usage": 1001,
  "reset_time": "2024-01-01T13:00:00Z"
}
```

**Solutions**:

1. Implement exponential backoff
2. Spread requests over time
3. Upgrade to higher rate limits
4. Use request queuing

#### CONCURRENT\_EXECUTION\_LIMIT

```json
{
  "error": "CONCURRENT_EXECUTION_LIMIT",
  "message": "Maximum concurrent workflow executions exceeded",
  "code": 4291,
  "current_executions": 5,
  "limit": 5
}
```

**Solutions**:

1. Wait for current executions to complete
2. Queue workflow executions
3. Optimize workflow performance
4. Upgrade plan for higher limits

## Error Response Format

All BroxiAI API errors follow this standard format:

```json
{
  "error": "ERROR_CODE",
  "message": "Human-readable error description",
  "code": 4001,
  "timestamp": "2024-01-01T12:00:00Z",
  "request_id": "req_abc123",
  "details": {
    "additional_context": "value"
  },
  "help_url": "https://docs.broxi.ai/errors/ERROR_CODE"
}
```

### Response Fields

* **error**: Machine-readable error code
* **message**: Human-readable error description
* **code**: Numeric error code
* **timestamp**: When the error occurred
* **request\_id**: Unique request identifier for support
* **details**: Additional context specific to the error
* **help\_url**: Link to specific documentation

## Error Handling Best Practices

### 1. Implement Proper Error Handling

```python
import requests
from typing import Dict, Any

def handle_api_response(response: requests.Response) -> Dict[str, Any]:
    """Handle API response with proper error checking"""
    
    if response.status_code == 200:
        return response.json()
    
    # Parse error response
    try:
        error_data = response.json()
    except ValueError:
        error_data = {"error": "UNKNOWN_ERROR", "message": response.text}
    
    # Handle specific error codes
    error_code = error_data.get("error")
    
    if error_code == "AUTH_TOKEN_INVALID":
        # Refresh token and retry
        refresh_token()
        return retry_request(response.request)
    
    elif error_code == "RATE_LIMIT_EXCEEDED":
        # Implement backoff
        reset_time = error_data.get("reset_time")
        implement_backoff(reset_time)
        return retry_request(response.request)
    
    elif error_code == "WORKFLOW_NOT_FOUND":
        # Check workflow existence
        workflow_id = error_data.get("workflow_id")
        verify_workflow_exists(workflow_id)
        
    else:
        # Log error and raise exception
        log_error(error_data)
        raise APIError(error_data)
    
    return error_data
```

### 2. Implement Retry Logic

```python
import time
import random
from functools import wraps

def retry_on_error(max_retries=3, backoff_factor=1):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except APIError as e:
                    error_code = e.error_data.get("error")
                    
                    # Don't retry on client errors (4xx)
                    if error_code.startswith("AUTH_") or error_code.startswith("WORKFLOW_NOT_"):
                        raise
                    
                    if attempt == max_retries - 1:
                        raise
                    
                    # Exponential backoff with jitter
                    delay = (backoff_factor * (2 ** attempt)) + random.uniform(0, 1)
                    time.sleep(delay)
            
            return None
        return wrapper
    return decorator

@retry_on_error(max_retries=3)
def make_api_call():
    # Your API call here
    pass
```

### 3. Log Errors Properly

```python
import logging
import json

def log_api_error(error_data: Dict[str, Any], request_context: Dict[str, Any]):
    """Log API errors with context"""
    
    log_entry = {
        "error_code": error_data.get("error"),
        "error_message": error_data.get("message"),
        "request_id": error_data.get("request_id"),
        "timestamp": error_data.get("timestamp"),
        "context": request_context
    }
    
    error_code = error_data.get("error", "")
    
    if error_code.startswith("5"):  # Server errors
        logging.error(f"Server error: {json.dumps(log_entry)}")
    elif error_code.startswith("4"):  # Client errors
        logging.warning(f"Client error: {json.dumps(log_entry)}")
    else:
        logging.info(f"API response: {json.dumps(log_entry)}")
```

## Debugging Tips

### 1. Use Request IDs

Every error response includes a `request_id`. Include this when contacting support:

```bash
# Include request ID in support requests
Error occurred with request ID: req_abc123
```

### 2. Enable Debug Logging

```python
import logging

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)

# Your API calls will now show detailed information
```

### 3. Test with Minimal Examples

When debugging, create minimal reproduction cases:

```python
# Minimal test case
def test_workflow_execution():
    workflow_id = "flow_simple_test"
    result = execute_workflow(workflow_id, {"input": "test"})
    assert result["status"] == "completed"
```

## Getting Help

When encountering errors:

1. **Check this reference** for specific error codes
2. **Review error details** in the response
3. **Check service status** at [status.broxi.ai](https://status.broxi.ai)
4. **Contact support** with error details and request ID

**Support Information to Include**:

* Complete error response (including request\_id)
* Steps to reproduce the error
* Account/workspace information
* Relevant configuration details

***

{% hint style="info" %}
Keep this reference handy for quick error resolution. Most errors can be resolved using the solutions provided here.
{% endhint %}
