Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Fix API exceptions handler

Tomas Valentaef1c1043e453
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 769c22088..2f050b988 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -2,14 +2,16 @@ import createClient from 'openapi-fetch'
import type { components, paths } from './schema.gen'
import { defaultHeaders } from './metadata'
-import { ConnectionConfig, SandboxError } from '../connectionConfig'
+import { ConnectionConfig } from '../connectionConfig'
+import { AuthenticationError, SandboxError } from '../errors'
import { createApiLogger } from '../logs'
-export class AuthenticationError extends SandboxError {
- constructor(message: any) {
- super(message)
- this.name = 'AuthenticationError'
+export function handleApiError(err?: { code: number; message: string; }) {
+ if (!err) {
+ return
}
+
+ return new SandboxError(`${err.code}: ${err.message}`)
}
class ApiClient {
@@ -17,10 +19,10 @@ class ApiClient {
constructor(
config: ConnectionConfig,
- opts?: {
+ opts: {
requireAccessToken?: boolean
requireApiKey?: boolean
- },
+ } = { requireAccessToken: false, requireApiKey: true },
) {
if (!opts?.requireApiKey && !config.apiKey) {
throw new AuthenticationError(
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index e84ccd043..a2942b823 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -1,4 +1,3 @@
-import { Code, ConnectError } from '@connectrpc/connect'
import { Logger } from './logs'
export const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'
@@ -17,116 +16,6 @@ export interface ConnectionOpts {
logger?: Logger
}
-export function handleApiError(err?: { code: number, message: string }) {
- if (!err) {
- return
- }
-
- return new SandboxError(`${err.code}: ${err.message}`)
-}
-
-// 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.`,
- )
-}
-
-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 412:
- return new InvalidPathError(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
-}
-
-export class SandboxError extends Error {
- constructor(message: any) {
- super(message)
- this.name = 'SandboxError'
- }
-}
-
-// [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)
-export class TimeoutError extends SandboxError {
- constructor(message: string) {
- super(message)
- this.name = 'TimeoutError'
- }
-}
-
-export class InvalidUserError extends SandboxError {
- constructor(message: string) {
- super(message)
- this.name = 'InvalidUserError'
- }
-}
-
-export class InvalidPathError extends SandboxError {
- constructor(message: string) {
- super(message)
- this.name = 'InvalidPathError'
- }
-}
-
-export class NotEnoughDiskSpaceError extends SandboxError {
- constructor(message: string) {
- super(message)
- this.name = 'NotEnoughDiskSpaceError'
- }
-}
-
-export class NotFoundError extends SandboxError {
- constructor(message: string) {
- super(message)
- this.name = 'NotFoundError'
- }
-}
-
export class ConnectionConfig {
readonly debug: boolean
readonly domain: string
diff --git a/packages/js-sdk/src/envd/api.ts b/packages/js-sdk/src/envd/api.ts
index 2735c95eb..fa7675490 100644
--- a/packages/js-sdk/src/envd/api.ts
+++ b/packages/js-sdk/src/envd/api.ts
@@ -3,6 +3,32 @@ import createClient from 'openapi-fetch'
import type { components, paths } from './schema.gen'
import { ConnectionConfig } from '../connectionConfig'
import { createApiLogger } from '../logs'
+import { SandboxError, InvalidUserError, InvalidPathError, NotFoundError, NotEnoughDiskSpaceError, formatSandboxTimeoutError } from '../errors'
+
+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 412:
+ return new InvalidPathError(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}`)
+ }
+ }
+}
+
class EnvdApiClient {
private readonly client: ReturnType<typeof createClient<paths>>
diff --git a/packages/js-sdk/src/envd/rpc.ts b/packages/js-sdk/src/envd/rpc.ts
new file mode 100644
index 000000000..322c03e7d
--- /dev/null
+++ b/packages/js-sdk/src/envd/rpc.ts
@@ -0,0 +1,29 @@
+import { Code, ConnectError } from '@connectrpc/connect'
+
+import { SandboxError, InvalidUserError, InvalidPathError, TimeoutError, formatSandboxTimeoutError } from '../errors'
+
+
+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
+}
diff --git a/packages/js-sdk/src/errors.ts b/packages/js-sdk/src/errors.ts
new file mode 100644
index 000000000..d2d69eb48
--- /dev/null
+++ b/packages/js-sdk/src/errors.ts
@@ -0,0 +1,59 @@
+// This is the message for the sandbox timeout error when the response code is 502/Unavailable
+export 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.`
+ )
+}
+
+export class SandboxError extends Error {
+ constructor(message: any) {
+ super(message)
+ this.name = 'SandboxError'
+ }
+}
+// [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)
+
+export class TimeoutError extends SandboxError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'TimeoutError'
+ }
+}
+
+export class InvalidUserError extends SandboxError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'InvalidUserError'
+ }
+}
+
+export class InvalidPathError extends SandboxError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'InvalidPathError'
+ }
+}
+
+export class NotEnoughDiskSpaceError extends SandboxError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'NotEnoughDiskSpaceError'
+ }
+}
+
+export class NotFoundError extends SandboxError {
+ constructor(message: string) {
+ super(message)
+ this.name = 'NotFoundError'
+ }
+}
+
+export class AuthenticationError extends SandboxError {
+ constructor(message: any) {
+ super(message)
+ this.name = 'AuthenticationError'
+ }
+}
\ No newline at end of file
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 34bfb5989..ca5e35302 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -1,18 +1,20 @@
export {
ApiClient,
- AuthenticationError,
} from './api'
export type { components, paths } from './api'
export {
- ConnectionConfig,
+ AuthenticationError,
SandboxError,
- DOMAIN,
- InvalidUserError,
- NotEnoughDiskSpaceError,
- NotFoundError,
InvalidPathError,
TimeoutError,
+ NotFoundError,
+ NotEnoughDiskSpaceError,
+ InvalidUserError,
+} from './errors'
+export {
+ ConnectionConfig,
+ DOMAIN,
} from './connectionConfig'
export type { Logger } from './logs'
export type { ConnectionOpts, Username } from './connectionConfig'
@@ -25,7 +27,7 @@ export {
FileType,
} from './sandbox/filesystem'
-export { ProcessError, ProcessExitError } from './sandbox/process/processHandle'
+export { ProcessExitError } from './sandbox/process/processHandle'
export type {
ProcessResult,
Stdout,
diff --git a/packages/js-sdk/src/sandbox/filesystem/index.ts b/packages/js-sdk/src/sandbox/filesystem/index.ts
index 84b0871fa..0e3d497bc 100644
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@ -11,10 +11,13 @@ import {
defaultUsername,
Username,
ConnectionOpts,
- handleRpcError,
- handleEnvdApiError,
- SandboxError,
} from '../../connectionConfig'
+import {
+ SandboxError
+} from '../../errors'
+import { handleEnvdApiError } from '../../envd/api'
+import { handleRpcError } from '../../envd/rpc'
+
import { EnvdApiClient } from '../../envd/api'
import { Filesystem as FilesystemService } from '../../envd/filesystem/filesystem_connect'
import { FileType as FsFileType, WatchDirResponse } from '../../envd/filesystem/filesystem_pb'
diff --git a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
index bfec3ef57..b74a892f0 100644
--- a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
@@ -1,5 +1,4 @@
-
-import { handleRpcError } from '../../connectionConfig'
+import { handleRpcError } from '../../envd/rpc'
import {
EventType,
WatchDirResponse,
diff --git a/packages/js-sdk/src/sandbox/process/index.ts b/packages/js-sdk/src/sandbox/process/index.ts
index a336a9b9d..989000824 100644
--- a/packages/js-sdk/src/sandbox/process/index.ts
+++ b/packages/js-sdk/src/sandbox/process/index.ts
@@ -3,6 +3,7 @@ import {
PromiseClient,
Transport,
} from '@connectrpc/connect'
+import { PlainMessage } from '@bufbuild/protobuf'
import { Process as ProcessService } from '../../envd/process/process_connect'
import {
@@ -10,9 +11,10 @@ import {
StartResponse,
ProcessConfig,
} from '../../envd/process/process_pb'
-import { ConnectionConfig, defaultUsername, Username, ConnectionOpts, SandboxError, handleRpcError } from '../../connectionConfig'
+import { ConnectionConfig, defaultUsername, Username, ConnectionOpts } from '../../connectionConfig'
+import { SandboxError } from '../../errors'
+import { handleRpcError } from '../../envd/rpc'
import { ProcessHandle, ProcessResult } from './processHandle'
-import { PlainMessage } from '@bufbuild/protobuf'
export interface ProcessRequestOpts extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> { }
diff --git a/packages/js-sdk/src/sandbox/process/processHandle.ts b/packages/js-sdk/src/sandbox/process/processHandle.ts
index 1ab2e295d..c7f56ce94 100644
--- a/packages/js-sdk/src/sandbox/process/processHandle.ts
+++ b/packages/js-sdk/src/sandbox/process/processHandle.ts
@@ -1,4 +1,5 @@
-import { handleRpcError, SandboxError } from '../../connectionConfig'
+import { handleRpcError } from '../../envd/rpc'
+import { SandboxError } from '../../errors'
import {
ConnectResponse,
StartResponse,
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index d6b1010ac..6754d7ddf 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -1,5 +1,6 @@
-import { ApiClient } from '../api'
-import { ConnectionConfig, ConnectionOpts, handleApiError } from '../connectionConfig'
+import { ApiClient, handleApiError } from '../api'
+import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
+
export interface RunningSandbox {
sandboxID: string
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 9eacfa58e..1448dddf4 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -22,5 +22,6 @@ from .sandbox.process.process_handle import (
ProcessResult,
Stderr,
Stdout,
+ ProcessExitException,
)
from .sandbox.filesystem.watch_handle import WatchHandle
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index f196bc948..54bff2c31 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,8 +1,10 @@
+import json
+
from importlib.metadata import version
from e2b.connection_config import ConnectionConfig
from e2b.api.metadata import default_headers
-from e2b.exceptions import AuthenticationException
+from e2b.exceptions import AuthenticationException, SandboxException
pydantic_version = version("pydantic")
@@ -16,11 +18,18 @@ else:
import e2b.api.v2.client.exceptions as exceptions
+def handle_api_exception(e: exceptions.ApiException):
+ body = json.loads(e.body) if e.body else {}
+ if "message" in body:
+ return SandboxException(f"{e.status}: {body['message']}")
+ return SandboxException(f"{e.status}: {e.body}")
+
+
class ApiClient(client.ApiClient):
def __init__(
self,
config: ConnectionConfig,
- require_api_key: bool = False,
+ require_api_key: bool = True,
require_access_token: bool = False,
*args,
**kwargs,
@@ -42,11 +51,13 @@ class ApiClient(client.ApiClient):
# See configuration.py for a list of all supported configuration parameters.
configuration = client.Configuration(host=config.api_url)
- configuration.api_key["ApiKeyAuth"] = config.api_key
- configuration.access_token = config.access_token
+ if config.api_key:
+ configuration.api_key["ApiKeyAuth"] = config.api_key
+ if config.access_token:
+ configuration.access_token = config.access_token
super().__init__(configuration, *args, **kwargs)
self.default_headers = default_headers
-__all__ = ["ApiClient", "client", "models"]
+__all__ = ["ApiClient", "client", "models", "exceptions"]
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index fc137b7ff..1a65c069f 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -36,7 +36,9 @@ class ConnectionConfig:
else:
self.request_timeout = REQUEST_TIMEOUT
- self.api_url = "http://localhost:3000" if debug else f"https://api.{domain}"
+ self.api_url = (
+ "http://localhost:3000" if debug else f"https://api.{self.domain}"
+ )
@staticmethod
def _get_request_timeout(
diff --git a/packages/python-sdk/e2b/envd/api.py b/packages/python-sdk/e2b/envd/api.py
index a7fff0603..3c786a8b6 100644
--- a/packages/python-sdk/e2b/envd/api.py
+++ b/packages/python-sdk/e2b/envd/api.py
@@ -1 +1,31 @@
+import requests
+from e2b.exceptions import (
+ SandboxException,
+ InvalidUserException,
+ InvalidPathException,
+ NotFoundException,
+ NotEnoughDiskSpaceException,
+ format_sandbox_timeout_exception,
+)
+
+
ENVD_API_FILES_ROUTE = "/files"
+
+
+# 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
diff --git a/packages/python-sdk/e2b/envd/rpc.py b/packages/python-sdk/e2b/envd/rpc.py
new file mode 100644
index 000000000..2710c9572
--- /dev/null
+++ b/packages/python-sdk/e2b/envd/rpc.py
@@ -0,0 +1,31 @@
+from connect.client import Code, ConnectException
+
+from e2b.exceptions import (
+ SandboxException,
+ InvalidUserException,
+ NotFoundException,
+ TimeoutException,
+ format_sandbox_timeout_exception,
+)
+
+
+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
diff --git a/packages/python-sdk/e2b/exceptions.py b/packages/python-sdk/e2b/exceptions.py
index 933c46557..c9cd30670 100644
--- a/packages/python-sdk/e2b/exceptions.py
+++ b/packages/python-sdk/e2b/exceptions.py
@@ -1,55 +1,9 @@
-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
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
index 4a09a9f56..3a4da0c3b 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
@@ -21,9 +21,9 @@ from e2b.connection_config import (
)
from e2b.exceptions import (
SandboxException,
- handle_envd_api_exception,
- handle_rpc_exception,
)
+from e2b.envd.api import handle_envd_api_exception
+from e2b.envd.rpc import handle_rpc_exception
from e2b.envd.filesystem import filesystem_connect, filesystem_pb2
from e2b.envd.permissions.permissions_pb2 import User
from e2b.envd.api import ENVD_API_FILES_ROUTE
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
index 2e9db5cf2..a1207780d 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
@@ -1,6 +1,6 @@
from typing import Any, Generator
-from e2b.exceptions import handle_rpc_exception
+from e2b.envd.rpc import handle_rpc_exception
from e2b.envd.filesystem.filesystem_pb2 import WatchDirResponse
# TODO: Export custom types
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 01070c1ad..2d28e42c7 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -10,6 +10,8 @@ from e2b.connection_config import ConnectionConfig
from e2b.envd.api import ENVD_API_FILES_ROUTE
from e2b.exceptions import SandboxException
+# TODO: Add logs
+
class Sandbox(SandboxApi):
_envd_port = 49982
@@ -35,7 +37,9 @@ class Sandbox(SandboxApi):
):
super().__init__()
- if sandbox_id and (metadata or timeout is not None):
+ if sandbox_id and (
+ metadata is not None or timeout is not None or template is not None
+ ):
raise SandboxException(
"Cannot set metadata or timeout when connecting to an existing sandbox. "
"Use Sandbox.connect method instead.",
diff --git a/packages/python-sdk/e2b/sandbox/process/main.py b/packages/python-sdk/e2b/sandbox/process/main.py
index c3a30a61c..f84ee8672 100644
--- a/packages/python-sdk/e2b/sandbox/process/main.py
+++ b/packages/python-sdk/e2b/sandbox/process/main.py
@@ -11,7 +11,8 @@ from e2b.connection_config import (
Username,
ConnectionConfig,
)
-from e2b.exceptions import handle_rpc_exception, SandboxException
+from e2b.exceptions import SandboxException
+from e2b.envd.rpc import handle_rpc_exception
@dataclass
diff --git a/packages/python-sdk/e2b/sandbox/process/process_handle.py b/packages/python-sdk/e2b/sandbox/process/process_handle.py
index 0e4028028..4ff5c1524 100644
--- a/packages/python-sdk/e2b/sandbox/process/process_handle.py
+++ b/packages/python-sdk/e2b/sandbox/process/process_handle.py
@@ -1,7 +1,8 @@
from dataclasses import dataclass
from typing import Optional, Callable, Any, Generator, Union, Tuple
-from e2b.exceptions import handle_rpc_exception, SandboxException
+from e2b.exceptions import SandboxException
+from e2b.envd.rpc import handle_rpc_exception
from e2b.envd.process import process_pb2
Stdout = str
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 0b0dc2330..1a7fda3bf 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -2,8 +2,9 @@ from dataclasses import dataclass
from typing import Optional, Dict, List
from datetime import datetime
-from e2b.api import ApiClient, models, client
+from e2b.api import ApiClient, models, client, exceptions
from e2b.connection_config import ConnectionConfig
+from e2b.api import handle_api_exception
@dataclass
@@ -31,21 +32,24 @@ class SandboxApi:
)
with ApiClient(config) as api_client:
- return [
- RunningSandbox(
- sandbox_id=SandboxApi._get_sandbox_id(
- sandbox.sandbox_id,
- sandbox.client_id,
- ),
- template_id=sandbox.template_id,
- name=sandbox.alias,
- metadata=sandbox.metadata,
- started_at=sandbox.started_at,
- )
- for sandbox in client.SandboxesApi(api_client).sandboxes_get(
- _request_timeout=config.request_timeout,
- )
- ]
+ try:
+ return [
+ RunningSandbox(
+ sandbox_id=SandboxApi._get_sandbox_id(
+ sandbox.sandbox_id,
+ sandbox.client_id,
+ ),
+ template_id=sandbox.template_id,
+ name=sandbox.alias,
+ metadata=sandbox.metadata,
+ started_at=sandbox.started_at,
+ )
+ for sandbox in client.SandboxesApi(api_client).sandboxes_get(
+ _request_timeout=config.request_timeout,
+ )
+ ]
+ except exceptions.ApiException as e:
+ raise handle_api_exception(e)
@staticmethod
def kill(
@@ -63,10 +67,13 @@ class SandboxApi:
)
with ApiClient(config) as api_client:
- client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(
- sandbox_id,
- _request_timeout=config.request_timeout,
- )
+ try:
+ client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(
+ sandbox_id,
+ _request_timeout=config.request_timeout,
+ )
+ except exceptions.ApiException as e:
+ raise handle_api_exception(e)
@staticmethod
def set_timeout(
@@ -85,11 +92,14 @@ class SandboxApi:
)
with ApiClient(config) as api_client:
- client.SandboxesApi(api_client).sandboxes_sandbox_id_timeout_post(
- sandbox_id,
- models.SandboxesSandboxIDTimeoutPostRequest(timeout=timeout),
- _request_timeout=config.request_timeout,
- )
+ try:
+ client.SandboxesApi(api_client).sandboxes_sandbox_id_timeout_post(
+ sandbox_id,
+ models.SandboxesSandboxIDTimeoutPostRequest(timeout=timeout),
+ _request_timeout=config.request_timeout,
+ )
+ except exceptions.ApiException as e:
+ raise handle_api_exception(e)
@staticmethod
def _create_sandbox(
@@ -109,16 +119,18 @@ class SandboxApi:
)
with ApiClient(config) as api_client:
- res = client.SandboxesApi(api_client).sandboxes_post(
- models.NewSandbox(
- templateID=template,
- metadata=metadata,
- timeout=timeout,
- ),
- _request_timeout=config.request_timeout,
- )
-
- return SandboxApi._get_sandbox_id(res.sandbox_id, res.client_id)
+ try:
+ res = client.SandboxesApi(api_client).sandboxes_post(
+ models.NewSandbox(
+ templateID=template,
+ metadata=metadata,
+ timeout=timeout,
+ ),
+ _request_timeout=config.request_timeout,
+ )
+ return SandboxApi._get_sandbox_id(res.sandbox_id, res.client_id)
+ except exceptions.ApiException as e:
+ raise handle_api_exception(e)
@staticmethod
def _get_sandbox_id(sandbox_id: str, client_id: str) -> str: