Errors and retries
Every API error carries:
codestatusrequest_idretryableretry_after_seconds- the number of
attemptsmade
Each error kind has its own class, so you can catch exactly what you handle.
import uuid
from svm import ApiError, Sandboxfrom svm.errors import SandboxFileNotFoundError, SandboxNotFoundError
try: Sandbox.connect(str(uuid.uuid4()))except SandboxNotFoundError as error: # Every API failure is an ApiError: HTTP status, error code, message and request id. assert isinstance(error, ApiError) print(error.status_code, error.code, error.message, error.request_id)
with Sandbox.create(template="base") as sandbox: try: sandbox.files.read_text("/no/such/file") except SandboxFileNotFoundError as error: print("missing file:", error.status_code, error.code)
# A command that runs past timeout_seconds is killed; the result says so. result = sandbox.commands.run("sleep 30", timeout_seconds=2) print("timed out:", result.timed_out)import { ApiError, FileNotFoundError, Sandbox, SandboxNotFoundError } from "@svm/sandbox";
try { await Sandbox.connect("00000000-0000-0000-0000-000000000000");} catch (error) { if (error instanceof SandboxNotFoundError) { console.log(error.statusCode, error.code, error.requestId); // 404 NOT_FOUND ... } else if (error instanceof ApiError) { console.log("API error", error.statusCode, error.code, error.message); } else { throw error; }}
const sandbox = await Sandbox.create({ template: "base" });try { try { await sandbox.files.readText("/no/such/file"); } catch (error) { if (!(error instanceof FileNotFoundError)) throw error; console.log("missing file:", error.code); }
// A command that runs past timeoutSeconds is killed; the result says so instead of throwing. const slow = await sandbox.commands.run("sleep 30", { timeoutSeconds: 2 }); if (slow.error === "timeout") console.log("timed out", slow.exitCode, slow.signal);} finally { await sandbox.kill();}// REST failures are *svm.APIError; errors.Is matches the kind (svm.ErrSandboxNotFound is also svm.ErrNotFound)._, err = client.ConnectSandbox(ctx, "sbx-does-not-exist", svm.ConnectSandboxOptions{})var apiErr *svm.APIErrorif errors.Is(err, svm.ErrSandboxNotFound) && errors.As(err, &apiErr) { fmt.Println("not found:", apiErr.Status, apiErr.Code, apiErr.RequestID)}
sandbox, err := client.CreateSandbox(ctx, svm.CreateSandboxOptions{Template: "base"})if err != nil { return err}defer sandbox.Kill(ctx)
// Data-plane failures are *svm.ProcessError, with the guest's code.files, err := sandbox.Files()if err != nil { return err}_, err = files.ReadText(ctx, "/tmp/missing.txt")var procErr *svm.ProcessErrorif errors.Is(err, svm.ErrFileNotFound) && errors.As(err, &procErr) { fmt.Println("missing file:", procErr.Code, procErr.Message)}
// A command that outlives its context ends with context.DeadlineExceeded.commands, err := sandbox.Commands()if err != nil { return err}short, cancel := context.WithTimeout(ctx, 2*time.Second)defer cancel()_, err = commands.Run(short, "sleep 30", svm.RunOptions{})if errors.Is(err, context.DeadlineExceeded) { fmt.Println("timed out:", err)}require "svm"
client = SVM::Client.newbegin SVM::Sandbox.connect("sbx-does-not-exist", client: client)rescue SVM::SandboxNotFoundError => e # REST errors are SVM::ApiError subclasses: HTTP status, error code and request id. puts "not found: HTTP #{e.status}, code #{e.code}, request #{e.request_id}"end
box = SVM::Sandbox.create(client: client, template: "base")begin begin box.files.read("/no/such/file") rescue SVM::FileNotFoundError => e # A data-plane failure: an SVM::ProcessError matched as FileNotFoundError; its code is the envd error code. puts "missing file: #{e.code} (#{SVM.error_kind(e)})" end
result = box.commands.run("sleep 30", timeout_seconds: 2) puts "command timed out" if result.error == "timeout" # the process was killed at its limitrescue SVM::ApiError => e puts "API error #{e.status} #{e.code}: #{e.api_message}"ensure box.killendimport dev.svm.sandbox.ApiException;import dev.svm.sandbox.Client;import dev.svm.sandbox.ProcessException;import dev.svm.sandbox.ProcessResult;import dev.svm.sandbox.RunOptions;import dev.svm.sandbox.Sandbox;
public class ErrorsExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try { Sandbox.connect(client, "sbx-does-not-exist"); } catch (ApiException.NotFound e) { // ApiException.SandboxNotFound for a sandbox System.out.println("HTTP " + e.status() + " " + e.code() + ": " + e.apiMessage() + " (request " + e.requestId() + ")"); }
try (Sandbox sandbox = Sandbox.create(client, "base")) { try { sandbox.files().readText("/no/such/file"); } catch (ProcessException.FileNotFound e) { // data-plane errors carry a code, not an HTTP status System.out.println(e.code() + " (" + e.grpcCode() + ")"); }
RunOptions options = new RunOptions(); options.timeoutSeconds = 2; ProcessResult slow = sandbox.commands().run("sleep 30", options); if (!slow.success()) { // a command that hits its timeout is ended, not thrown System.out.println("ended: exit " + slow.exitCode + " signal=" + slow.signal + " error=" + slow.error); } } catch (ApiException e) { // every API error: status(), code(), retryable() System.out.println("API error " + e.status() + " " + e.code()); } }}Error kinds
Section titled “Error kinds”| Kind | Code | Python and TypeScript | Go errors.Is |
|---|---|---|---|
| authentication | UNAUTHENTICATED |
AuthenticationError |
ErrAuthentication |
| permission denied | PERMISSION_DENIED |
PermissionDeniedError |
ErrPermissionDenied |
| not found | NOT_FOUND |
NotFoundError |
ErrNotFound |
| conflict | ALREADY_EXISTS, IDEMPOTENCY_CONFLICT |
ConflictError |
ErrConflict |
| precondition | FAILED_PRECONDITION, SANDBOX_NOT_RUNNING, SANDBOX_PAUSED, TEMPLATE_NOT_READY |
PreconditionError |
ErrPrecondition |
| invalid argument | INVALID_ARGUMENT |
InvalidArgumentError |
ErrInvalidArgument |
| rate limited | RATE_LIMITED |
RateLimitedError |
ErrRateLimited |
| quota exceeded | QUOTA_EXCEEDED, RESOURCE_EXHAUSTED |
QuotaExceededError |
ErrQuotaExceeded |
| billing blocked | BILLING_BLOCKED |
BillingBlockedError |
ErrBillingBlocked |
| unavailable | UNAVAILABLE |
UnavailableError |
ErrUnavailable |
| timeout | no answer in time, or a wait that gave up | TimeoutError |
ErrTimeout |
| transport | connection failed or reset | TransportError |
ErrTransport |
Ruby uses the Python class names under SVM::. Java nests them in ApiException (ApiException.NotFound).
Specific subclasses name what is missing or full. Each is also its general kind, so catching NotFoundError still works:
SandboxNotFoundErrorVolumeNotFoundErrorSecretNotFoundError- the file-not-found error
NotEnoughSpaceErrorSandboxNotRunningErrorTemplateErrorBuildError
What is retried for you
Section titled “What is retried for you”| Situation | Retried |
|---|---|
A GET, HEAD, PUT or DELETE that failed to connect, timed out, or got 502, 503 or 504 |
Yes |
| A POST that failed the same way | Yes, with the same idempotency key, so it cannot create twice |
429 RATE_LIMITED |
Yes, after the server’s Retry-After |
Other 4xx, QUOTA_EXCEEDED, BILLING_BLOCKED |
Never |
500 INTERNAL |
Only when the error says retryable |
The default is six attempts with jittered exponential backoff (250 ms doubling up to 8 s), and a 10-second timeout per attempt.