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

# Sandbox Error Handling

> Error classes and exception handling in the HopX Python SDK. Handle API errors, network errors, agent errors, and validation errors gracefully. Learn about error types, error handling patterns, and best practices for robust error handling in your applications. Includes error class reference and handling examples.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## Overview

The Python SDK provides a comprehensive error hierarchy for handling different types of errors. All errors inherit from `HopxError` and provide detailed error information.

## Import

```python theme={null}
from hopx_ai import (
    HopxError,
    APIError,
    AuthenticationError,
    NotFoundError,
    ValidationError,
    RateLimitError,
    ResourceLimitError,
    ServerError,
    NetworkError,
    TimeoutError,
    AgentError,
    FileNotFoundError,
    FileOperationError,
    CodeExecutionError,
    CommandExecutionError,
    DesktopNotAvailableError
)
```

## Base Error

### `HopxError`

Base exception for all HopX SDK errors.

**Fields:**

* `message` (`str`): Error message
* `code` (`str`, optional): Error code
* `request_id` (`str`, optional): Request ID for debugging
* `status_code` (`int`, optional): HTTP status code
* `details` (`Dict[str, Any]`, optional): Additional error details

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.create(template="invalid-template")
except HopxError as e:
    print(f"Error: {e.message}")
    print(f"Code: {e.code}")
```

**Expected Output:**

```
Error: Template not found
Code: TEMPLATE_NOT_FOUND
```

***

## API Errors

### `APIError`

Base class for API request failures.

**Inherits from:** `HopxError`

**Fields:**

* `status_code` (`int`): HTTP status code

***

### `AuthenticationError`

Authentication failed (401).

**Inherits from:** `APIError`

**When raised:**

* Invalid or missing API key
* Expired authentication token

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.create(template="code-interpreter", api_key="invalid")
except AuthenticationError:
    print("Invalid API key")
```

**Expected Output:**

```
Invalid API key
```

***

### `NotFoundError`

Resource not found (404).

**Inherits from:** `APIError`

**When raised:**

* Sandbox not found
* Template not found
* File not found

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.connect("non-existent-id")
except NotFoundError:
    print("Sandbox not found")
```

**Expected Output:**

```
Sandbox not found
```

***

### `ValidationError`

Request validation failed (400).

**Inherits from:** `APIError`

**Fields:**

* `field` (`str`, optional): Field that failed validation

**When raised:**

* Invalid parameters
* Missing required fields
* Invalid data format

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.create(template="", template_id="")
except ValidationError as e:
    print(f"Validation failed: {e.message}")
    if e.field:
        print(f"Field: {e.field}")
```

**Expected Output:**

```
Validation failed: Either template or template_id must be provided
Field: template
```

***

### `RateLimitError`

Rate limit exceeded (429).

**Inherits from:** `APIError`

**Fields:**

* `retry_after` (`int`, optional): Seconds to wait before retrying

**When raised:**

* Too many requests in a time period

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.create(template="code-interpreter")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
```

**Expected Output:**

```
Rate limited. Retry after 60 seconds
```

***

### `ResourceLimitError`

Resource limit exceeded.

**Inherits from:** `APIError`

**Fields:**

* `limit` (`int`): Resource limit
* `current` (`int`): Current usage
* `available` (`int`): Available resources
* `upgrade_url` (`str`, optional): URL to upgrade plan

**When raised:**

* Exceeded sandbox quota
* Insufficient resources

**Example:**

```python theme={null}
try:
    sandbox = Sandbox.create(template="code-interpreter")
except ResourceLimitError as e:
    print(f"Limit exceeded: {e.current}/{e.limit}")
    if e.upgrade_url:
        print(f"Upgrade at: {e.upgrade_url}")
```

**Expected Output:**

```
Limit exceeded: 10/10
Upgrade at: https://console.hopx.dev/upgrade
```

***

### `ServerError`

Server error (5xx).

**Inherits from:** `APIError`

**When raised:**

* Internal server error
* Service unavailable

***

## Network Errors

### `NetworkError`

Network communication failed.

**Inherits from:** `HopxError`

**When raised:**

* Connection errors
* DNS resolution failures

***

### `TimeoutError`

Request timed out.

**Inherits from:** `NetworkError`

**When raised:**

* Request exceeded timeout
* Operation took too long

**Example:**

```python theme={null}
try:
    result = sandbox.run_code("import time; time.sleep(300)", timeout=60)
except TimeoutError:
    print("Execution timed out")
```

**Expected Output:**

```
Execution timed out
```

***

## Agent Errors

### `AgentError`

Base error for agent operations.

**Inherits from:** `HopxError`

***

### `FileNotFoundError`

File or directory not found in sandbox.

**Inherits from:** `AgentError`

**Fields:**

* `path` (`str`): Path that was not found

**Example:**

```python theme={null}
try:
    content = sandbox.files.read("/nonexistent/file.txt")
except FileNotFoundError as e:
    print(f"File not found: {e.path}")
```

**Expected Output:**

```
File not found: /nonexistent/file.txt
```

***

### `FileOperationError`

File operation failed.

**Inherits from:** `AgentError`

**Fields:**

* `operation` (`str`): Operation that failed

**Example:**

```python theme={null}
try:
    sandbox.files.write("/readonly/file.txt", "content")
except FileOperationError as e:
    print(f"File operation failed: {e.operation}")
```

**Expected Output:**

```
File operation failed: write
```

***

### `CodeExecutionError`

Code execution failed.

**Inherits from:** `AgentError`

**Fields:**

* `language` (`str`): Language that failed

**Example:**

```python theme={null}
try:
    result = sandbox.run_code("invalid syntax here", language="python")
except CodeExecutionError as e:
    print(f"Code execution failed: {e.message}")
```

**Expected Output:**

```
Code execution failed: SyntaxError: invalid syntax
```

***

### `CommandExecutionError`

Command execution failed.

**Inherits from:** `AgentError`

**Fields:**

* `command` (`str`): Command that failed

**Example:**

```python theme={null}
try:
    result = sandbox.commands.run("nonexistent-command")
except CommandExecutionError as e:
    print(f"Command failed: {e.command}")
```

**Expected Output:**

```
Command failed: nonexistent-command
```

***

### `DesktopNotAvailableError`

Desktop automation not available in this sandbox.

**Inherits from:** `AgentError`

**Fields:**

* `missing_dependencies` (`List[str]`): Missing dependencies
* `docs_url` (`str`, optional): Documentation URL
* `install_command` (`str`, optional): Installation command

**Example:**

```python theme={null}
try:
    screenshot = sandbox.desktop.screenshot()
except DesktopNotAvailableError as e:
    print(f"Desktop not available: {e.message}")
    if e.install_command:
        print(f"Install with: {e.install_command}")
```

**Expected Output:**

```
Desktop not available: Desktop automation requires desktop-enabled template
Install with: Use template with desktop support
```

***

## Error Handling Examples

### Example 1: Basic Error Handling

```python theme={null}
from hopx_ai import Sandbox, HopxError

try:
    sandbox = Sandbox.create(template="code-interpreter")
    result = sandbox.run_code("print('Hello')")
except HopxError as e:
    print(f"Error: {e.message}")
    if hasattr(e, 'status_code'):
        print(f"Status: {e.status_code}")
```

**Expected Output:**

```
Hello
```

### Example 2: Specific Error Handling

```python theme={null}
from hopx_ai import Sandbox, AuthenticationError, NotFoundError, ValidationError

try:
    sandbox = Sandbox.create(template="code-interpreter")
except AuthenticationError:
    print("Authentication failed. Check your API key.")
except NotFoundError:
    print("Template not found.")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
```

**Expected Output:**

```
Sandbox created successfully
```

### Example 3: Retry on Rate Limit

```python theme={null}
from hopx_ai import Sandbox, RateLimitError
import time

def create_sandbox_with_retry():
    max_retries = 3
    for attempt in range(max_retries):
        try:
            return Sandbox.create(template="code-interpreter")
        except RateLimitError as e:
            if attempt < max_retries - 1:
                wait_time = e.retry_after or 60
                print(f"Rate limited. Waiting {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                raise
```

**Expected Output:**

```
Sandbox created successfully (after retry if needed)
```

***

## Related Classes

* **[Models](/sdk/python/models)** - Data models
* **[Sandbox](/sdk/python/sandbox)** - Sandbox operations that may raise errors

## See Also

* [Models](/sdk/python/models) - Learn about data models
* [Core Concepts: Errors](/core-concepts/errors) - Learn about error handling

## Next Steps

Now that you understand error handling, explore:

* [Error Handling Basics](/cookbooks/getting-started/error-handling) - Practical error handling patterns
* [Sandbox Operations](/sdk/python/sandbox) - See errors in action
* [API Errors](/api/concepts/errors) - Understand API error responses
* **[CLI Reference](/cli/introduction)** - Use HopX from the command line
* [Troubleshooting](/api/concepts/troubleshooting) - Common issues and solutions
