Skip to content

Commit 1287fbb

Browse files
committed
Generalize 404 error handling
1 parent 39504d9 commit 1287fbb

File tree

5 files changed

+42
-51
lines changed

5 files changed

+42
-51
lines changed

packages/js-sdk/src/api/index.ts

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import createClient, { FetchResponse } from 'openapi-fetch'
33
import type { components, paths } from './schema.gen'
44
import { defaultHeaders } from './metadata'
55
import { ConnectionConfig } from '../connectionConfig'
6-
import { AuthenticationError, RateLimitError, SandboxError } from '../errors'
6+
import { AuthenticationError, RateLimitError, SandboxError, NotFoundError } from '../errors'
77
import { createApiLogger } from '../logs'
88

99
export function handleApiError(
@@ -18,28 +18,31 @@ export function handleApiError(
1818
return
1919
}
2020

21+
const content = response.error?.message ?? response.error
22+
2123
if (response.response.status === 401) {
2224
const message = 'Unauthorized, please check your credentials.'
23-
const content = response.error?.message ?? response.error
2425

25-
if (content) {
26-
return new AuthenticationError(`${message} - ${content}`)
27-
}
28-
return new AuthenticationError(message)
26+
return content
27+
? new AuthenticationError(`${message} - ${content}`)
28+
: new AuthenticationError(message)
2929
}
3030

3131
if (response.response.status === 429) {
3232
const message = 'Rate limit exceeded, please try again later'
33-
const content = response.error?.message ?? response.error
3433

35-
if (content) {
36-
return new RateLimitError(`${message} - ${content}`)
37-
}
38-
return new RateLimitError(message)
34+
return content
35+
? new RateLimitError(`${message} - ${content}`)
36+
: new RateLimitError(message)
37+
}
38+
39+
if (response.response.status === 404) {
40+
return content
41+
? new NotFoundError(`${content}`)
42+
: new NotFoundError('Not found')
3943
}
4044

41-
const message = response.error?.message ?? response.error
42-
return new errorClass(`${response.response.status}: ${message}`, stackTrace)
45+
return new errorClass(`${response.response.status}: ${content}`, stackTrace)
4346
}
4447

4548
/**
@@ -58,15 +61,15 @@ class ApiClient {
5861
if (opts?.requireApiKey && !config.apiKey) {
5962
throw new AuthenticationError(
6063
'API key is required, please visit the Team tab at https://e2b.dev/dashboard to get your API key. ' +
61-
'You can either set the environment variable `E2B_API_KEY` ' +
62-
"or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })"
64+
'You can either set the environment variable `E2B_API_KEY` ' +
65+
"or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })"
6366
)
6467
}
6568

6669
if (opts?.requireAccessToken && !config.accessToken) {
6770
throw new AuthenticationError(
6871
'Access token is required, please visit the Personal tab at https://e2b.dev/dashboard to get your access token. ' +
69-
'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'
72+
'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'
7073
)
7174
}
7275

packages/js-sdk/src/sandbox/sandboxApi.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export interface SandboxApiOpts
1818
ConnectionOpts,
1919
'apiKey' | 'headers' | 'debug' | 'domain' | 'requestTimeoutMs'
2020
>
21-
> {}
21+
> { }
2222

2323
/**
2424
* Options for creating a new Sandbox.
@@ -224,7 +224,7 @@ export interface SandboxMetrics {
224224
}
225225

226226
export class SandboxApi {
227-
protected constructor() {}
227+
protected constructor() { }
228228

229229
/**
230230
* Kill the sandbox specified by sandbox ID.
@@ -357,10 +357,6 @@ export class SandboxApi {
357357
signal: config.getSignal(opts?.requestTimeoutMs),
358358
})
359359

360-
if (res.error?.code === 404) {
361-
throw new NotFoundError(`Sandbox ${sandboxId} not found`)
362-
}
363-
364360
const err = handleApiError(res)
365361
if (err) {
366362
throw err
@@ -380,10 +376,6 @@ export class SandboxApi {
380376
signal: config.getSignal(opts?.requestTimeoutMs),
381377
})
382378

383-
if (res.error?.code === 404) {
384-
throw new NotFoundError(`Sandbox ${sandboxId} not found`)
385-
}
386-
387379
const err = handleApiError(res)
388380
if (err) {
389381
throw err
@@ -485,7 +477,7 @@ export class SandboxApi {
485477
await this.kill(res.data!.sandboxID, opts)
486478
throw new TemplateError(
487479
'You need to update the template to use the new SDK. ' +
488-
'You can do this by running `e2b template build` in the directory with the template.'
480+
'You can do this by running `e2b template build` in the directory with the template.'
489481
)
490482
}
491483

packages/python-sdk/e2b/api/__init__.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
AuthenticationException,
1414
SandboxException,
1515
RateLimitException,
16+
NotFoundException,
1617
)
1718
from e2b.api.client.types import Response
1819

@@ -37,23 +38,30 @@ def handle_api_exception(
3738
except json.JSONDecodeError:
3839
body = {}
3940

41+
content = body.get("message", str(e.content))
42+
4043
if e.status_code == 401:
4144
message = f"{e.status_code}: Unauthorized, please check your credentials."
42-
if body.get("message"):
43-
message += f" - {body['message']}"
44-
return AuthenticationException(message)
45+
46+
return (
47+
AuthenticationException(f"{message} - {content}")
48+
if content
49+
else AuthenticationException(message)
50+
)
4551

4652
if e.status_code == 429:
4753
message = f"{e.status_code}: Rate limit exceeded, please try again later."
48-
if body.get("message"):
49-
message += f" - {body['message']}"
50-
return RateLimitException(message)
51-
52-
if "message" in body:
53-
return default_exception_class(
54-
f"{e.status_code}: {body['message']}"
55-
).with_traceback(stack_trace)
56-
return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(
54+
55+
return (
56+
RateLimitException(f"{message} - {content}")
57+
if content
58+
else RateLimitException(message)
59+
)
60+
61+
if e.status_code == 404:
62+
return NotFoundException(content) if content else NotFoundException("Not found")
63+
64+
return default_exception_class(f"{e.status_code}: {content}").with_traceback(
5765
stack_trace
5866
)
5967

packages/python-sdk/e2b/sandbox_async/sandbox_api.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,6 @@ async def _cls_get_info(
7676
client=api_client,
7777
)
7878

79-
if res.status_code == 404:
80-
raise NotFoundException(f"Sandbox {sandbox_id} not found")
81-
8279
if res.status_code >= 300:
8380
raise handle_api_exception(res)
8481

@@ -142,9 +139,6 @@ async def _cls_set_timeout(
142139
body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),
143140
)
144141

145-
if res.status_code == 404:
146-
raise NotFoundException(f"Paused sandbox {sandbox_id} not found")
147-
148142
if res.status_code >= 300:
149143
raise handle_api_exception(res)
150144

packages/python-sdk/e2b/sandbox_sync/sandbox_api.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,6 @@ def _cls_get_info(
7575
client=api_client,
7676
)
7777

78-
if res.status_code == 404:
79-
raise NotFoundException(f"Sandbox {sandbox_id} not found")
80-
8178
if res.status_code >= 300:
8279
raise handle_api_exception(res)
8380

@@ -141,9 +138,6 @@ def _cls_set_timeout(
141138
body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),
142139
)
143140

144-
if res.status_code == 404:
145-
raise NotFoundException(f"Sandbox {sandbox_id} not found")
146-
147141
if res.status_code >= 300:
148142
raise handle_api_exception(res)
149143

0 commit comments

Comments
 (0)