Skip to main content
Learn how to handle errors gracefully in your sandbox operations for robust, production-ready applications.

Basic Error Handling

Handle errors with try-except blocks:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
from hopx_ai.errors import SandboxError, CodeExecutionError

def execute_code_safe(code: str):
    """Execute code with error handling"""
    try:
        with Sandbox.create(template="code-interpreter") as sandbox:
            result = sandbox.run_code(code)
            
            if not result.success:
                return {
                    "success": False,
                    "error": result.stderr,
                    "exit_code": result.exit_code
                }
            
            return {
                "success": True,
                "output": result.stdout
            }
    except CodeExecutionError as e:
        return {
            "success": False,
            "error": f"Code execution failed: {e.message}",
            "request_id": e.request_id
        }
    except SandboxError as e:
        return {
            "success": False,
            "error": f"Sandbox error: {e.message}",
            "request_id": e.request_id
        }

# Example usage
result = execute_code_safe("print(1/0)")  # Will fail
if not result["success"]:
    print(f"Error: {result['error']}")

Handle Specific Error Types

Catch specific error types for better error handling:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
from hopx_ai.errors import (
    AuthenticationError,
    NotFoundError,
    ValidationError,
    RateLimitError,
    APIError
)

def handle_specific_errors():
    """Handle specific error types"""
    try:
        sandbox = Sandbox.create(template="code-interpreter")
    except AuthenticationError:
        print("Check your API key")
    except NotFoundError:
        print("Resource not found")
    except ValidationError as e:
        print(f"Invalid input: {e.message}")
    except RateLimitError as e:
        print(f"Rate limit exceeded. Retry after {e.retry_after}s")
    except APIError as e:
        print(f"API error: {e.message}")
        if e.request_id:
            print(f"Request ID: {e.request_id}")

Retry Logic

Implement retry logic for transient errors:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
from hopx_ai.errors import RateLimitError, ServerError
import time

def execute_with_retry(code: str, max_retries: int = 3):
    """Execute code with retry logic"""
    for attempt in range(max_retries):
        try:
            with Sandbox.create(template="code-interpreter") as sandbox:
                result = sandbox.run_code(code)
                return result
        except (RateLimitError, ServerError) as e:
            if attempt < max_retries - 1:
                wait_time = e.retry_after if hasattr(e, 'retry_after') and e.retry_after else 2 ** attempt
                time.sleep(wait_time)
                continue
            raise
    return None

# Example usage
result = execute_with_retry("print('Hello')")

Logging and Debugging

Log errors with request IDs for debugging:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
from hopx_ai.errors import HopxError
import logging

logger = logging.getLogger(__name__)

def execute_with_logging(code: str):
    """Execute code with error logging"""
    try:
        with Sandbox.create(template="code-interpreter") as sandbox:
            result = sandbox.run_code(code)
            return result
    except HopxError as e:
        logger.error(f"Sandbox error: {e.message}")
        if e.request_id:
            logger.error(f"Request ID: {e.request_id}")  # Include in support ticket
        raise

# Example usage
try:
    result = execute_with_logging("print('Hello')")
except Exception as e:
    logger.exception("Failed to execute code")

Best Practices Summary

Catch specific exception types for better error handling:
except AuthenticationError:
    # Handle authentication errors
except RateLimitError:
    # Handle rate limit errors
Check error properties for debugging:
except CodeExecutionError as e:
    print(f"Error: {e.message}")
    print(f"Request ID: {e.request_id}")
Implement retry logic for transient errors (rate limits, server errors).
Always log request IDs for support tickets:
if e.request_id:
    logger.error(f"Request ID: {e.request_id}")
Don’t catch all exceptions without handling them:
# ❌ Bad: Swallows all errors
# try:
#     result = sandbox.run_code(code)
# except:
#     pass
Don’t ignore error details - they help with debugging:
# ❌ Bad: Loses error information
# except Exception:
#     return {"error": "Something went wrong"}

# ✅ Good: Preserves error information
except CodeExecutionError as e:
    return {"error": e.message, "request_id": e.request_id}

Next Steps