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

# Error Handling

> Learn about error handling and troubleshooting in the OcularAI SDK

# Error Handling and Troubleshooting

The OcularAI SDK provides comprehensive error handling capabilities to help you diagnose and address issues in your applications. This guide explains the available error types and best practices for handling them effectively.

## Error Hierarchy

<Info>
  All SDK errors inherit from the base `OcularError` class, making it easy to catch any SDK-related issue.
</Info>

All errors raised by the SDK inherit from the base `OcularError` class, allowing you to catch all SDK-specific errors with a single exception handler:

```python theme={null}
from ocular import Ocular
from ocular.utils.errors import OcularError

try:
    ocular = Ocular(api_key="invalid_key")
    project = ocular.workspace("invalid_id").project("invalid_id")
except OcularError as e:
    print(f"An OcularAI SDK error occurred: {e}")
```

## Specific Error Types

<Check>
  Using specific error types allows you to implement targeted error handling strategies in your application.
</Check>

The SDK uses specific error types to help you handle different error scenarios appropriately:

| Error Type              | Description                  | Common Causes                                       |
| ----------------------- | ---------------------------- | --------------------------------------------------- |
| `AuthenticationError`   | Issues with authentication   | Invalid API key, expired credentials                |
| `ValidationError`       | Invalid parameters or inputs | Incorrect ID format, missing required fields        |
| `ResourceNotFoundError` | Requested resource not found | Non-existent workspace, project, version, or export |
| `RateLimitError`        | API rate limits exceeded     | Too many requests in a short period                 |
| `ServerError`           | Server-side errors           | Internal server issues, maintenance                 |
| `NetworkError`          | Network connectivity issues  | Connection problems, timeouts                       |
| `TimeoutError`          | Request timeout              | Slow network, large dataset downloads               |

## Example: Handling Specific Error Types

You can catch specific error types to handle different error scenarios differently:

```python theme={null}
from ocular import Ocular
from ocular.utils.errors import (
    OcularError,
    AuthenticationError,
    ResourceNotFoundError,
    NetworkError,
    TimeoutError
)

try:
    # Initialize the SDK
    ocular = Ocular(api_key="your_api_key")

    # Get workspace, project, version, and export
    workspace = ocular.workspace("workspace_id")
    project = workspace.project("project_id")
    version = project.version("version_id")
    export = version.export("export_id")

    # Download the dataset
    dataset = export.download()

    print(f"Dataset downloaded to: {dataset}")

except AuthenticationError as e:
    print(f"Authentication failed: {e}")
    print("Please check your API key and try again.")

except ResourceNotFoundError as e:
    print(f"Resource not found: {e}")
    print("Please verify your workspace, project, version, and export IDs.")

except (NetworkError, TimeoutError) as e:
    print(f"Network or timeout error: {e}")
    print("Please check your internet connection and try again.")

except OcularError as e:
    print(f"An OcularAI SDK error occurred: {e}")

except Exception as e:
    print(f"An unexpected error occurred: {e}")
```

## Retry Mechanism

<Tip>
  For operations that might be affected by transient network issues, configuring proper retry settings can significantly improve reliability.
</Tip>

The SDK includes a built-in retry mechanism for transient errors like network issues or server errors. You can configure this mechanism when initializing the SDK:

```python theme={null}
from ocular import Ocular

# Configure retry behavior
ocular = Ocular(
    api_key="your_api_key",
    max_retries=5,          # Maximum number of retry attempts
    backoff_factor=1.0      # Exponential backoff factor
)
```

With these settings, the SDK will retry failed requests up to 5 times with exponential backoff between attempts.

## Debug Mode

<Note>
  Debug mode provides detailed logs that are invaluable when troubleshooting issues with the SDK.
</Note>

For troubleshooting, you can enable debug mode to get more detailed logs:

```python theme={null}
from ocular import Ocular

# Enable debug mode
ocular = Ocular(api_key="your_api_key", debug=True)
```

## Common Error Scenarios and Solutions

<Warning>
  Being familiar with these common error scenarios can save significant troubleshooting time during development.
</Warning>

| Scenario                       | Error                   | Solution                                                             |
| ------------------------------ | ----------------------- | -------------------------------------------------------------------- |
| Invalid API Key                | `AuthenticationError`   | Check that your API key is correct and has the necessary permissions |
| Incorrect Workspace/Project ID | `ResourceNotFoundError` | Verify the IDs in the OcularAI Foundry platform                      |
| Slow Downloads                 | `TimeoutError`          | Increase the timeout setting or use a more reliable network          |
| "Too Many Requests" error      | `RateLimitError`        | Implement exponential backoff, reduce request frequency              |
| Server Maintenance             | `ServerError`           | Wait and retry after some time                                       |

## Logging and Debugging

<Check>
  Proper logging configuration is essential for production applications to help diagnose issues that occur in deployed environments.
</Check>

When troubleshooting issues, check the SDK logs for more information:

```python theme={null}
from ocular import Ocular
from ocular.utils.logging import setup_logging

# Set up detailed logging
logger = setup_logging(level="DEBUG", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Initialize the SDK and perform operations
ocular = Ocular(api_key="your_api_key")
```
