Error Handling Examples

Learn how to handle different types of errors that may occur when using AI Computer. These examples demonstrate best practices for error handling and recovery.

Setup Errors

Handle errors that may occur during client setup:

1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_setup_errors():
5    try:
6        # Initialize client
7        client = SandboxClient()
8        
9        # Handle setup response
10        setup_response = await client.setup()
11        if not setup_response.success:
12            print(f"Setup failed: {setup_response.error}")
13            return None
14            
15        return client
16        
17    except Exception as e:
18        print(f"Unexpected error during setup: {str(e)}")
19        return None
20
21async def main():
22    # Try to set up the client
23    client = await handle_setup_errors()
24    if client is None:
25        print("Could not initialize client")
26        return
27        
28    try:
29        # Use the client
30        response = await client.execute_code("print('Hello')")
31        if response.success:
32            print(response.data['output'])
33    finally:
34        await client.cleanup()
35
36asyncio.run(main())

Execution Errors

Handle different types of code execution errors:

1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_execution_errors():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Example 1: Syntax Error
10        code1 = """
11print("Unclosed string
12"""
13        response1 = await client.execute_code(code1)
14        if not response1.success:
15            print("Syntax Error:", response1.error)
16            
17        # Example 2: Runtime Error
18        code2 = """
19x = undefined_variable
20print(x)
21"""
22        response2 = await client.execute_code(code2)
23        if not response2.success:
24            print("Runtime Error:", response2.error)
25            
26        # Example 3: Memory Error
27        code3 = """
28# Create a large list
29large_list = list(range(10**8))
30"""
31        response3 = await client.execute_code(code3)
32        if not response3.success:
33            print("Memory Error:", response3.error)
34            
35    finally:
36        await client.cleanup()
37
38asyncio.run(handle_execution_errors())

Timeout Handling

Handle timeouts in long-running operations:

1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_timeouts():
5    # Create client with short timeout
6    client = SandboxClient(timeout=5)  # 5 second timeout
7    await client.setup()
8    
9    try:
10        # Code that will timeout
11        code = """
12import time
13print("Starting long operation...")
14time.sleep(10)  # Will exceed timeout
15print("Done!")  # Won't be reached
16"""
17        print("Executing code with timeout...")
18        
19        async for event in client.execute_code_stream(code):
20            if event.type == 'stdout':
21                print("Output:", event.data)
22            elif event.type == 'error':
23                if 'timeout' in event.data.lower():
24                    print("Operation timed out")
25                else:
26                    print("Error:", event.data)
27                break
28                
29    finally:
30        await client.cleanup()
31
32asyncio.run(handle_timeouts())

Resource Cleanup

Ensure proper cleanup even when errors occur:

1import asyncio
2from ai_computer import SandboxClient
3
4async def ensure_cleanup():
5    client = None
6    
7    try:
8        # Setup
9        client = SandboxClient()
10        setup_response = await client.setup()
11        if not setup_response.success:
12            print(f"Setup failed: {setup_response.error}")
13            return
14            
15        # Simulate an error during execution
16        code = """
17raise Exception("Something went wrong!")
18"""
19        response = await client.execute_code(code)
20        if not response.success:
21            print("Execution failed:", response.error)
22            
23    except Exception as e:
24        print(f"Unexpected error: {str(e)}")
25        
26    finally:
27        # Always attempt cleanup if client exists
28        if client is not None:
29            try:
30                await client.cleanup()
31                print("Cleanup successful")
32            except Exception as e:
33                print(f"Cleanup failed: {str(e)}")
34
35asyncio.run(ensure_cleanup())

Best Practices

1. Check All Response Objects

Always check response.success before accessing response.data.

2. Use try/finally

Ensure cleanup is called in a finally block to handle all error cases.

3. Handle Specific Errors

Catch and handle specific error types appropriately for better error recovery.

4. Graceful Degradation

Implement fallback behavior when errors occur to maintain application stability.