---
title: Errors
description: The error classes the SDK throws and lets you throw, every kind of system error with its HTTP status, and the codes of JwtError.
related:
  - /lunas/return-errors
  - /sdk/handler-spec
  - /sdk/ctx
---

A failed call throws a `LunaCallError`. It carries a `code` and `data` when the handler failed with an error it declares, and a `kind` when Luna could not run the call or the handler failed in some other way.

```ts luna/lunas/shop.ts
import { defineLuna, LunaCallError, t } from "luna";
import { Wallet } from "./wallet.ts";

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  handlers: (h) => ({
    buy: h({ args: { user: t.string(), amount: t.int() }, errors: { Short: t.object({ have: t.int() }), TryLater: t.json() } }, async (ctx, { user, amount }) => {
      try {
        return await ctx.call(Wallet, { id: user }).charge({ amount });
      } catch (e) {
        if (!(e instanceof LunaCallError)) throw e;
        if (e.code === "Short") throw e;
        if (e.retryable) ctx.fail("TryLater", { kind: e.kind });
        throw e;
      }
    }),
  }),
});
```

## Reference

### LunaError

The error `ctx.fail` throws. Throwing one yourself does the same.

```ts
import { LunaError } from "luna";
```

| Prop | Type | Default | Description |
| - | - | - | - |
| `code` | `string` | - | The error's code, one the handler declares in errors. |
| `data?` | `unknown` | `null` | Data of the type the handler declares for the code. |
| `keep?` | `boolean` | `false` | The failed call keeps what it wrote and sent. |

Construct it with `new LunaError(code, data?, { keep? })`.

### LunaCallError

What a call to another luna throws when it fails.

| Prop | Type | Default | Description |
| - | - | - | - |
| `code` | `string \| undefined` | - | The declared error's code, for an error the handler declares. |
| `data` | `unknown` | - | The declared error's data, or null. |
| `kind` | `SystemKind \| undefined` | - | The system error's kind, for any other failure. |
| `retryable` | `boolean` | - | True for Overloaded, Timeout, OutcomeUnknown, Unavailable and NoRoom. Never true for a declared error. |

### SystemKind

Each kind has a page under Errors. A call over HTTP answers with the status shown.

| Kind | Status | Retryable | Meaning |
| --- | --- | --- | --- |
| [`Invalid`](/errors/invalid) | 400 | No | The call was malformed, such as an unknown luna type or handler, or arguments that do not match. |
| [`NotFound`](/errors/not-found) | 404 | No | The handler requires an existing luna, and this one has no stored data. |
| [`Overloaded`](/errors/overloaded) | 429 | Yes | Too many calls are running or waiting on the luna. |
| [`Timeout`](/errors/timeout) | 504 | Yes | The call's deadline passed. |
| [`OutcomeUnknown`](/errors/outcome-unknown) | 502 | Yes | The luna stopped after it received the call, so the handler may or may not have run. Retry with an idempotency key. |
| [`Unavailable`](/errors/unavailable) | 503 | Yes | The luna cannot run now, and the call never started. |
| [`Quarantined`](/errors/quarantined) | 503 | No | The luna crashed too often and is held back. |
| [`NoRoom`](/errors/no-room) | 503 | Yes | The luna type reserves its limits, and no machine has room for them now. The call never started. |
| [`OutOfMemory`](/errors/out-of-memory) | 500 | No | The luna reached its memory limit, and the same call would again. |
| [`Cancelled`](/errors/cancelled) | 409 | No | The durable run was cancelled, or the caller went away. |
| [`Unauthorized`](/errors/unauthorized) | 401 | No | The call came without a valid key or token, or with one that may not be used here. |
| [`Denied`](/errors/denied) | 403 | No | `onBeforeConnect` refused the caller, or a file URL's signature was wrong. |
| [`QuotaExceeded`](/errors/quota-exceeded) | 429 | No | The organisation or tenant reached a quota or its spending cap. |
| [`PaymentRequired`](/errors/payment-required) | 402 | No | Work is paused until a payment goes through. |
| [`Suspended`](/errors/suspended) | 403 | No | Luna suspended the organisation. |
| [`Closed`](/errors/closed) | None | No | The client, or its connection to the luna, is closed. |
| [`Internal`](/errors/internal) | 500 | No | The handler threw an error it does not declare, failed with a code it does not declare, or returned a result that does not match returns. |

A declared error answers 422 over HTTP, unless the route maps its code to another status.

### HttpError

Thrown to a caller through an SDK when the handler answers with a web `Response` whose status is 400 or above.

```ts
import { HttpError } from "luna";
```

| Prop | Type | Default | Description |
| - | - | - | - |
| `status` | `number` | - | The response's status. |
| `headers` | `Headers` | - | The response's headers. |
| `body` | `unknown` | - | The response's body. |

### IsolateError

Thrown by a run of an [isolate](/sdk/isolate) that failed.

```ts
import { IsolateError } from "luna";
```

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The name of the error the code threw, such as TypeError, or CpuLimitExceeded, MemoryLimitExceeded or TimeoutExceeded when a limit stopped it. |
| `message` | `string` | - | The error's message. |
| `logs` | `IsolateLog[]` | - | What the code logged before it failed. |
| `snippetStack` | `string` | - | The stack trace inside the code that ran. |

### RunCancelled

Thrown in a durable run that was cancelled, at its first new step, sleep or wait. Its message is `the run was cancelled`.

```ts
import { RunCancelled } from "luna";
```

### RunCodeChanged

Fails a durable run when a deploy changed the order of its steps, sleeps and waits. The message names the operation that changed. Finish or cancel runs before you change their code.

```ts
import { RunCodeChanged } from "luna";
```

### JwtError

A `LunaError` that the token checks in `luna/auth` throw. Thrown from `onBeforeConnect`, it refuses the caller with its `code`, as `ctx.fail(code)` does.

```ts
import { JwtError } from "luna/auth";
```

| Code | Meaning |
| --- | --- |
| `malformed` | The token is not a well-formed JWT, or lacks a claim it needs, such as `exp`. |
| `bad_signature` | The signature does not verify. |
| `expired` | The token's `exp` has passed, or a DPoP proof is too old. |
| `not_yet_valid` | The token's `nbf` is still to come. |
| `wrong_issuer` | The token's `iss` is not the one expected. |
| `wrong_audience` | The token's `aud` is not the one expected. |
| `unknown_key` | No key fits the token's `kid`. |
| `bad_algorithm` | The token's algorithm is not allowed, or the key cannot verify it. |
| `bad_proof` | A DPoP proof is malformed or signed by another key than the token is bound to. |
| `replayed` | A DPoP proof was used before. |

## Good to know

- A declared error from a luna you call passes through your handler when your handler declares the same code. Otherwise your caller gets `Internal`.
- A failed call undoes its writes and sends nothing, unless it failed with `keep: true`.
- An app's client throws `ConnectionError`, covered in [connect](/sdk/connect).

## Examples

### Keep a failed attempt

The attempt counts toward a lockout even though the call fails.

```ts luna/lunas/shop.ts
login: h({ args: { password: t.string() }, errors: { WrongPassword: t.object({ left: t.int() }) } }, (ctx, { password }) => {
  ctx.db.attempts.insert({ at: ctx.now() });
  const left = 5 - ctx.db.attempts.count();
  if (password !== ctx.env.SHOP_PASSWORD) ctx.fail("WrongPassword", { left }, { keep: true });
  ctx.db.attempts.delete({});
}),
```

### Report what broke in an isolate

```ts luna/lunas/shop.ts
price: h({ args: { code: t.string() } }, async (ctx, { code }) => {
  try {
    const { result } = await ctx.isolates.rule.run(code);
    return result;
  } catch (e) {
    if (e instanceof IsolateError) return { error: e.name, message: e.message };
    throw e;
  }
}),
```
