# Handling sandbox API errors in TypeScript: what to retry, what to surface, what to recover

> A practical guide to the error classes in @sandscale/sdk: which failures the SDK retries for you, which it never retries, and how to recover a sandbox start that timed out.

A practical guide to the error classes in @sandscale/sdk: which failures the SDK retries for you, which it never retries, and how to recover a sandbox start that timed out.

November 23, 2026 · · The Sandscale team

The happy path for a sandbox is three calls: create, run, stop. The code that decides whether your agent platform is pleasant to operate is everything around those calls when one of them fails. A quota was hit. A policy said no. The network dropped halfway through a start. The organization’s kill switch was pulled.

This post walks through how the Sandscale TypeScript SDK reports those failures, what it already retries for you, and the handling you still need to write. Everything here comes from the [errors reference](https://sandscale.dev/docs/api/errors) and the type definitions shipped in `@sandscale/sdk` 1.0.0 on npm.

## The error body and the error classes

When the API refuses a request, it answers with an HTTP status and a JSON body:

```json
{
  "error": {
    "code": "lease_expired",
    "message": "the lease has ended",
    "request_id": "8f3c2a71-...",
    "details": { "lease_id": "..." }
  }
}
```

That example is the one from the docs. The rule that matters: `code` is stable and meant for programs; `message` is for people and can change. Branch on the code, log the message.

The SDK turns every refusal into a `SandscaleError` with `status`, `code`, `requestId`, `details` and `region`, and then into a more specific subclass based on the status and code. The ones you will meet most:

| Class | When | What to do |
| --- | --- | --- |
| `InvalidRequestError` | 400, 413, 422 | Fix the request. Retrying unchanged will fail the same way. |
| `AuthenticationError` | 401 | The key is missing, expired or revoked. Stop and alert. |
| `PermissionDeniedError` | 403 | The key lacks a scope, or policy refused. Surface it; do not retry. |
| `NotFoundError` | 404 | Wrong ID, or not visible to this caller. The API does not say which. |
| `ConflictError` | 409 | The sandbox is in the wrong state (paused, ended, busy). Read its state, then decide. |
| `LimitExceededError` | 402, or a quota or limit code | A plan or usage limit refused it. Has `retryAfterMs` and `limitInfo`. |
| `RateLimitError` | 429 | Too many requests. Wait `retryAfterMs`. |
| `EntitlementError` | The plan does not include the feature | Surface it with the plan the server names. |
| `KillSwitchError` | A kill switch stopped the call | Stop all work for this organization. Never retry in a loop. |
| `ServerError` / `ServiceUnavailableError` | 5xx | Retry with backoff when `retryable` is true. |
| `ConnectionError` | No answer at all | The connection failed or the call timed out. See the section on starts below. |

All of them are exported from the package, so `instanceof` checks work.

## What the SDK already retries

Before writing a retry loop, know what the client does on its own, because double retries multiply load exactly when the service is struggling.

In 1.0.0, the client retries only safe calls, `GET` and `HEAD`, and only on `429`, `502`, `503` and `504` or a connection failure. The default is two retries (`maxRetries` in the client options). It waits for the server’s `Retry-After` when one is sent, and otherwise backs off with jitter. It never retries a kill switch, an entitlement refusal or a region error.

It does **not** retry `POST`, `PUT` or `DELETE`. That means `sandboxes.create`, `sandboxes.run`, `writeFile` and `stop` are each sent once. That is deliberate: a create that is retried blindly can start two sandboxes.

## A small wrapper for the calls you own

Here is a pattern for wrapping an agent’s sandbox call. It turns errors into one of three outcomes your agent loop can act on: try again later, give up and tell a person, or stop everything.

```ts
import {
  Sandscale,
  SandscaleError,
  RateLimitError,
  LimitExceededError,
  KillSwitchError,
  ServerError,
  PermissionDeniedError,
  AuthenticationError,
} from '@sandscale/sdk';

type Outcome<T> =
  | { kind: 'ok'; value: T }
  | { kind: 'retry'; afterMs: number; reason: string }
  | { kind: 'fail'; reason: string; requestId?: string }
  | { kind: 'halt'; reason: string };

export async function attempt<T>(fn: () => Promise<T>): Promise<Outcome<T>> {
  try {
    return { kind: 'ok', value: await fn() };
  } catch (e) {
    if (!(e instanceof SandscaleError)) throw e;
    if (e instanceof KillSwitchError) return { kind: 'halt', reason: e.code };
    if (e instanceof AuthenticationError) return { kind: 'halt', reason: 'credential rejected' };
    if (e instanceof RateLimitError || e instanceof LimitExceededError) {
      return { kind: 'retry', afterMs: e.retryAfterMs || 30_000, reason: e.code };
    }
    if (e instanceof ServerError && e.retryable) {
      return { kind: 'retry', afterMs: e.retryAfterMs || 5_000, reason: e.code };
    }
    if (e instanceof PermissionDeniedError) {
      return { kind: 'fail', reason: `not allowed: ${e.code}`, requestId: e.requestId };
    }
    return { kind: 'fail', reason: `${e.status} ${e.code}`, requestId: e.requestId };
  }
}
```

A few choices in there are worth calling out.

**A kill switch halts, not retries.** If someone in your organization pulled the switch, they meant it. A worker that retries every five seconds is fighting the person trying to stop it.

**Limits retry with a long default.** A `LimitExceededError` without a `Retry-After` usually means a plan or usage limit, which will not clear in a few seconds. Thirty seconds is only an example value; set your own policy, and for a monthly allowance, the right answer is to stop and tell someone.

**Keep the request ID.** It matches the `X-Request-ID` response header, and it is what support needs to find your call.

## Fail closed is a feature

The errors reference describes one behavior worth designing around. When the server cannot decide a request, for example because it cannot read a policy, check a permission or write the audit entry, it refuses with `503` instead of letting the request through. Codes such as `policy_unavailable`, `authorization_unavailable` and `audit_unavailable` mean exactly that.

From the client side these look like ordinary transient failures, and the wrapper above retries them with backoff. The important part is what you do not do: do not fall back to running the agent’s code somewhere else “until the sandbox service is back”. The refusal is the control working.

## Recovering a start that timed out

The hardest case is a `ConnectionError` on `sandboxes.create`. The request may never have reached the server, or the server may have started a sandbox and the answer was lost. The SDK will not retry it, and you should not retry it blindly either.

Label every sandbox you start with something unique to the attempt, then check for it before trying again:

```ts
import { randomUUID } from 'node:crypto';
import { Sandscale, ConnectionError } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY from the environment

async function startOnce(template: string) {
  const attemptId = randomUUID();
  try {
    return await sandscale.sandboxes.create({
      template,
      timeoutSeconds: 1800,
      labels: { attempt: attemptId },
    });
  } catch (e) {
    if (!(e instanceof ConnectionError)) throw e;
    // The start may or may not have happened. Look before starting another.
    const page = await sandscale.sandboxes.list({ limit: 100 });
    const found = page.data.find((s) => s.labels?.attempt === attemptId);
    if (found) return found;
    throw e; // nothing started; the caller can decide to try again
  }
}
```

Two notes on this. `list` without a region reads every live region and reports a region it could not read in `pages[].error` instead of failing the whole call, so check those entries if you run in more than one region. And the `timeoutSeconds` on the create is your backstop: even if your process crashes and never finds the orphan, the sandbox stops by itself when its timeout runs out. The server default is 3600 seconds and the maximum is 86400.

## Errors from the code, not the API

One distinction trips people up. If the command you run inside the sandbox fails, that is not an API error. `sandboxes.run` succeeds and returns a `RunResult` with a non-zero `exitCode`, and the `timedOut` and `oomKilled` flags tell you if the command hit its time limit or ran out of memory.

Those results belong in front of the model, because they describe its code. API errors belong in front of your operators, because they describe your platform. Keeping the two apart makes both easier to act on: the agent can fix a failing test, and a person can fix a missing scope.

## A checklist

- Branch on `code` and class, never on `message`.
- Let the SDK retry reads; do not wrap them in a second retry loop.
- Never retry `create` blindly; label the attempt and look first.
- Treat `KillSwitchError` as stop-everything.
- Log `requestId` with every failure.
- Always set `timeoutSeconds` on create, so a lost sandbox cleans itself up.
- Report command failures to the model and API failures to people.

The full list of status codes is on the [errors page](https://sandscale.dev/docs/api/errors), and every SDK method is in the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript).

---
Source: https://sandscale.dev/blog/handling-sandscale-api-errors-typescript
