Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Improve exception handling
Tomas Valenta3c0e73c55b01
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex a5a6003bf..e84ccd043 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -43,6 +43,8 @@ export function handleEnvdApiError(err: {return new InvalidPathError(err.message)case 404:return new NotFoundError(err.message)+ case 412:+ return new InvalidPathError(err.message)case 502:return formatSandboxTimeoutError(err.message)case 507:diff --git a/packages/js-sdk/src/sandbox/process/processHandle.ts b/packages/js-sdk/src/sandbox/process/processHandle.tsindex 2cdc0f789..1ab2e295d 100644--- a/packages/js-sdk/src/sandbox/process/processHandle.ts+++ b/packages/js-sdk/src/sandbox/process/processHandle.ts@@ -1,4 +1,4 @@-import { SandboxError } from '../../connectionConfig'+import { handleRpcError, SandboxError } from '../../connectionConfig'import {ConnectResponse,StartResponse,@@ -124,6 +124,8 @@ export class ProcessHandle implements Omit<ProcessResult, 'exitCode' | 'error'>,return this.result}}+ } catch (e) {+ throw handleRpcError(e)} finally {this.handleDisconnect()}diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 087fcbba3..9eacfa58e 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -1,9 +1,21 @@from .api import (ApiClient,- AuthenticationException,client,)-from .connection_config import ConnectionConfig, Username+from .connection_config import (+ ConnectionConfig,+ DOMAIN,+)++from .exceptions import (+ InvalidPathException,+ SandboxException,+ TimeoutException,+ NotFoundException,+ InvalidUserException,+ NotEnoughDiskSpaceException,+ AuthenticationException,+)from .sandbox.main import Sandboxfrom .sandbox.process.process_handle import (ProcessHandle,diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex 7d111fe51..f196bc948 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -1,11 +1,8 @@from importlib.metadata import version-from e2b.connection_config import ConnectionConfig, SandboxException+from e2b.connection_config import ConnectionConfigfrom e2b.api.metadata import default_headers---class AuthenticationException(SandboxException):- pass+from e2b.exceptions import AuthenticationExceptionpydantic_version = version("pydantic")diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex 132e58503..fc137b7ff 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -2,7 +2,6 @@ import osfrom typing import Literal, Optional-DOMAIN = os.getenv("E2B_DOMAIN", "e2b.dev")DEBUG = os.getenv("E2B_DEBUG", "false") == "true"API_KEY = os.getenv("E2B_API_KEY")@@ -11,96 +10,6 @@ ACCESS_TOKEN = os.getenv("E2B_ACCESS_TOKEN")REQUEST_TIMEOUT: float = 30 # 30s-# // This is the message for the sandbox timeout error when the response code is 502/Unavailable-# function formatSandboxTimeoutError(message: string) {-# return new TimeoutError(-# `${message}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`,-# )-# }---def format_sandbox_timeout_error(message: str):- return TimeoutException(- f"{message}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout."- )---# export function handleEnvdApiError(err: {-# code: number;-# message: string;-# } | undefined) {-# switch (err?.code) {-# case 400:-# return new InvalidUserError(err.message)-# case 403:-# return new InvalidPathError(err.message)-# case 404:-# return new NotFoundError(err.message)-# case 502:-# return formatSandboxTimeoutError(err.message)-# case 507:-# return new NotEnoughDiskSpaceError(err.message)-# default:-# if (err) {-# return new SandboxError(`${err.code}: ${err.message}`)-# }-# }-# }--# export function handleRpcError(err: unknown) {-# if (err instanceof ConnectError) {-# switch (err.code) {-# case Code.InvalidArgument:-# return new InvalidUserError(err.message)-# case Code.NotFound:-# return new InvalidPathError(err.message)-# case Code.Unavailable:-# return formatSandboxTimeoutError(err.message)-# case Code.Canceled:-# return new TimeoutError(-# `${err.message}: This error is likely due to exceeding 'requestTimeoutMs'. You can pass the request timeout value as an option when making the request.`,-# )-# case Code.DeadlineExceeded:-# return new TimeoutError(-# `${err.message}: This error is likely due to exceeding 'timeoutMs' — the total time a long running request can be active. It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout.`,-# )-# default:-# return new SandboxError(`${err.code}: ${err.message}`)-# }-# }--# return err-# }---class SandboxException(Exception):- pass---# [unknown] is sometimes caused by the sandbox timeout when the request is not processed-# [unavailable] is caused by sandbox timeout-# [canceled] is caused by exceeding request timeout-# [deadline_exceeded] is caused by exceeding the timeout (for process handlers, watch, etc)-class TimeoutException(SandboxException):- pass---class NotEnoughDiskSpaceException(SandboxException):- pass---class NotFoundException(SandboxException):- pass---class InvalidPathException(SandboxException):- pass---class InvalidUserException(SandboxException):- pass--class ConnectionConfig:def __init__(self,diff --git a/packages/python-sdk/e2b/exceptions.py b/packages/python-sdk/e2b/exceptions.pynew file mode 100644index 000000000..933c46557--- /dev/null+++ b/packages/python-sdk/e2b/exceptions.py@@ -0,0 +1,82 @@+import requests++from connect.client import Code, ConnectException+++def format_sandbox_timeout_exception(message: str):+ return TimeoutException(+ f"{message}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout."+ )+++# TODO: Improve the messages+def handle_envd_api_exception(res: requests.Response):+ if res.status_code == 400:+ return InvalidUserException(res.json().get("message"))+ elif res.status_code == 403:+ return InvalidPathException(res.json().get("message"))+ elif res.status_code == 404:+ return NotFoundException(res.json().get("message"))+ elif res.status_code == 412:+ return InvalidPathException(res.json().get("message"))+ elif res.status_code == 502:+ return format_sandbox_timeout_exception(res.json().get("message"))+ elif res.status_code == 507:+ return NotEnoughDiskSpaceException(res.json().get("message"))+ elif res.status_code >= 400:+ return SandboxException(f"{res.status_code}: {res.json().get('message')}")+ return None+++def handle_rpc_exception(e: Exception):+ if isinstance(e, ConnectException):+ if e.status == Code.invalid_argument:+ return InvalidUserException(e.message)+ elif e.status == Code.not_found:+ return NotFoundException(e.message)+ elif e.status == Code.unavailable:+ return format_sandbox_timeout_exception(e.message)+ elif e.status == Code.canceled:+ return TimeoutException(+ f"{e.message}: This error is likely due to exceeding 'requestTimeoutMs'. You can pass the request timeout value as an option when making the request."+ )+ elif e.status == Code.deadline_exceeded:+ return TimeoutException(+ f"{e.message}: This error is likely due to exceeding 'timeoutMs' — the total time a long running request can be active. It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout."+ )+ else:+ return SandboxException(f"{e.status}: {e.message}")+ else:+ return e+++class SandboxException(Exception):+ pass+++# [unknown] is sometimes caused by the sandbox timeout when the request is not processed+# [unavailable] is caused by sandbox timeout+# [canceled] is caused by exceeding request timeout+# [deadline_exceeded] is caused by exceeding the timeout (for process handlers, watch, etc)+class TimeoutException(SandboxException):+ pass+++class NotEnoughDiskSpaceException(SandboxException):+ pass+++class NotFoundException(SandboxException):+ pass+++class InvalidPathException(SandboxException):+ pass+++class InvalidUserException(SandboxException):+ pass+++class AuthenticationException(SandboxException):+ passdiff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.pyindex daf5da2d7..4a09a9f56 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py@@ -15,7 +15,15 @@ from typing import ()from e2b.sandbox.filesystem.watch_handle import WatchHandle-from e2b.connection_config import SandboxException, Username, ConnectionConfig+from e2b.connection_config import (+ Username,+ ConnectionConfig,+)+from e2b.exceptions import (+ SandboxException,+ handle_envd_api_exception,+ handle_rpc_exception,+)from e2b.envd.filesystem import filesystem_connect, filesystem_pb2from e2b.envd.permissions.permissions_pb2 import Userfrom e2b.envd.api import ENVD_API_FILES_ROUTE@@ -79,6 +87,10 @@ class Filesystem:timeout=self._connection_config.get_request_timeout(request_timeout),)+ err = handle_envd_api_exception(r)+ if err:+ raise err+if format == "text":return r.textelif format == "bytes":@@ -104,21 +116,28 @@ class Filesystem:timeout=self._connection_config.get_request_timeout(request_timeout),)+ err = handle_envd_api_exception(r)+ if err:+ raise err+def list(self,path: str,user: Username = "user",request_timeout: Optional[float] = None,) -> List[filesystem_pb2.EntryInfo]:- res = self._rpc.list_dir(- filesystem_pb2.ListDirRequest(- path=path,- user=User(username=user),- ),- timeout=self._connection_config.get_request_timeout(request_timeout),- )+ try:+ res = self._rpc.list_dir(+ filesystem_pb2.ListDirRequest(+ path=path,+ user=User(username=user),+ ),+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )- return [entry for entry in res.entries]+ return [entry for entry in res.entries]+ except Exception as e:+ raise handle_rpc_exception(e)def exists(self,@@ -136,10 +155,11 @@ class Filesystem:)return True- except connect.ConnectException as e:- if e.status == connect.Code.already_exists:- return False- raise+ except Exception as e:+ if isinstance(e, connect.ConnectException):+ if e.status == connect.Code.not_found:+ return False+ raise handle_rpc_exception(e)def remove(self,@@ -147,13 +167,16 @@ class Filesystem:user: Username = "user",request_timeout: Optional[float] = None,) -> None:- self._rpc.remove(- filesystem_pb2.RemoveRequest(- path=path,- user=User(username=user),- ),- timeout=self._connection_config.get_request_timeout(request_timeout),- )+ try:+ self._rpc.remove(+ filesystem_pb2.RemoveRequest(+ path=path,+ user=User(username=user),+ ),+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )+ except Exception as e:+ raise handle_rpc_exception(e)def rename(self,@@ -162,14 +185,17 @@ class Filesystem:user: Username = "user",request_timeout: Optional[float] = None,) -> None:- self._rpc.move(- filesystem_pb2.MoveRequest(- source=old_path,- destination=new_path,- user=User(username=user),- ),- timeout=self._connection_config.get_request_timeout(request_timeout),- )+ try:+ self._rpc.move(+ filesystem_pb2.MoveRequest(+ source=old_path,+ destination=new_path,+ user=User(username=user),+ ),+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )+ except Exception as e:+ raise handle_rpc_exception(e)def make_dir(self,@@ -187,10 +213,11 @@ class Filesystem:)return True- except connect.ConnectException as e:- if e.status == connect.Code.already_exists:- return False- raise+ except Exception as e:+ if isinstance(e, connect.ConnectException):+ if e.status == connect.Code.already_exists:+ return False+ raise handle_rpc_exception(e)def watch(self,@@ -213,6 +240,9 @@ class Filesystem:try:start_event = next(events)+ if not start_event.HasField("start"):+ raise SandboxException("Failed to start watch: start event not found")+return WatchHandle(events=events)except Exception as e:- raise SandboxException(f"Failed to start watch: {e}")+ raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.pyindex c0894ff53..2e9db5cf2 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py@@ -1,4 +1,5 @@from typing import Any, Generator+from e2b.exceptions import handle_rpc_exceptionfrom e2b.envd.filesystem.filesystem_pb2 import WatchDirResponse@@ -23,5 +24,7 @@ class WatchHandle(Generator):for event in self._events:if event.HasField("filesystem"):yield event.filesystem+ except Exception as e:+ raise handle_rpc_exception(e)finally:self.close()diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.pyindex b61237b62..01070c1ad 100644--- a/packages/python-sdk/e2b/sandbox/main.py+++ b/packages/python-sdk/e2b/sandbox/main.py@@ -6,8 +6,9 @@ from typing import Optional, Dictfrom e2b.sandbox.filesystem.filesystem import Filesystemfrom e2b.sandbox.process.main import Processfrom e2b.sandbox.sandbox_api import SandboxApi-from e2b.connection_config import ConnectionConfig, SandboxException+from e2b.connection_config import ConnectionConfigfrom e2b.envd.api import ENVD_API_FILES_ROUTE+from e2b.exceptions import SandboxExceptionclass Sandbox(SandboxApi):diff --git a/packages/python-sdk/e2b/sandbox/process/main.py b/packages/python-sdk/e2b/sandbox/process/main.pyindex 2e9fd06a6..c3a30a61c 100644--- a/packages/python-sdk/e2b/sandbox/process/main.py+++ b/packages/python-sdk/e2b/sandbox/process/main.py@@ -7,7 +7,11 @@ from typing import Dict, List, Optional, Literal, overload, Union, Callablefrom e2b.envd.permissions import permissions_pb2from e2b.envd.process import process_connect, process_pb2from e2b.sandbox.process.process_handle import ProcessHandle, ProcessResult-from e2b.connection_config import SandboxException, Username, ConnectionConfig+from e2b.connection_config import (+ Username,+ ConnectionConfig,+)+from e2b.exceptions import handle_rpc_exception, SandboxException@dataclass@@ -38,34 +42,40 @@ class Process:self,request_timeout: Optional[float] = None,) -> List[ProcessInfo]:- res = self._rpc.list(- process_pb2.ListRequest(),- timeout=self._connection_config.get_request_timeout(request_timeout),- )- return [- ProcessInfo(- pid=p.pid,- tag=p.tag,- cmd=p.config.cmd,- args=list(p.config.args),- envs=dict(p.config.envs),- cwd=p.config.cwd,+ try:+ res = self._rpc.list(+ process_pb2.ListRequest(),+ timeout=self._connection_config.get_request_timeout(request_timeout),)- for p in res.processes- ]+ return [+ ProcessInfo(+ pid=p.pid,+ tag=p.tag,+ cmd=p.config.cmd,+ args=list(p.config.args),+ envs=dict(p.config.envs),+ cwd=p.config.cwd,+ )+ for p in res.processes+ ]+ except Exception as e:+ raise handle_rpc_exception(e)def kill(self,pid: int,request_timeout: Optional[float] = None,):- self._rpc.send_signal(- process_pb2.SendSignalRequest(- process=process_pb2.ProcessSelector(pid=pid),- signal=process_pb2.Signal.SIGNAL_SIGKILL,- ),- timeout=self._connection_config.get_request_timeout(request_timeout),- )+ try:+ self._rpc.send_signal(+ process_pb2.SendSignalRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ signal=process_pb2.Signal.SIGNAL_SIGKILL,+ ),+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )+ except Exception as e:+ raise handle_rpc_exception(e)def send_stdin(self,@@ -73,15 +83,18 @@ class Process:data: str,request_timeout: Optional[float] = None,):- self._rpc.send_input(- process_pb2.SendInputRequest(- process=process_pb2.ProcessSelector(pid=pid),- input=process_pb2.ProcessInput(- stdin=data.encode(),+ try:+ self._rpc.send_input(+ process_pb2.SendInputRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ input=process_pb2.ProcessInput(+ stdin=data.encode(),+ ),),- ),- timeout=self._connection_config.get_request_timeout(request_timeout),- )+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )+ except Exception as e:+ raise handle_rpc_exception(e)@overloaddef run(@@ -169,13 +182,16 @@ class Process:try:start_event = next(events)+ if not start_event.HasField("event"):+ raise SandboxException("Failed to start process: start event not found")+return ProcessHandle(pid=start_event.event.start.pid,handle_kill=lambda: self.kill(start_event.event.start.pid),events=events,)except Exception as e:- raise SandboxException(f"Failed to start process: {e}")+ raise handle_rpc_exception(e)def connect(self,@@ -196,10 +212,15 @@ class Process:try:start_event = next(events)+ if not start_event.HasField("event"):+ raise SandboxException(+ "Failed to connect to process: start event not found"+ )+return ProcessHandle(pid=start_event.event.start.pid,handle_kill=lambda: self.kill(start_event.event.start.pid),events=events,)except Exception as e:- raise SandboxException(f"Failed to start process: {e}")+ raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/process/process_handle.py b/packages/python-sdk/e2b/sandbox/process/process_handle.pyindex 1ec5faba6..0e4028028 100644--- a/packages/python-sdk/e2b/sandbox/process/process_handle.py+++ b/packages/python-sdk/e2b/sandbox/process/process_handle.py@@ -1,7 +1,7 @@from dataclasses import dataclassfrom typing import Optional, Callable, Any, Generator, Union, Tuple-from e2b.connection_config import SandboxException+from e2b.exceptions import handle_rpc_exception, SandboxExceptionfrom e2b.envd.process import process_pb2Stdout = str@@ -80,6 +80,8 @@ class ProcessHandle:exit_code=event.event.end.exit_code,error=event.event.end.error,)+ except Exception as e:+ raise handle_rpc_exception(e)finally:self.disconnect()