# Errors and retries

> Terminal errors, retried errors, retry policies and paused invocations.

Source: https://cairnflow.dev/docs/develop/errors-retries

A handler can end in three ways besides returning a value: fail for good, be retried, or pause
until someone fixes the cause. Which one you get depends on what you throw.

| You throw | Outcome | Journal |
|---|---|---|
| `TerminalError(message, code)` | Invocation ends `failed` with `code` and `message`. Not retried | Kept; the failure is the result |
| Any other error | The turn fails and is **retried** with backoff | Kept; completed steps replay, only unfinished work runs again |
| `PauseError(message, code)` | Invocation is `paused`, waiting for an operator | Kept; `resume` continues from the same point |

All three are exported from `@cairnflow/sdk`.

## TerminalError

Use it for failures a retry cannot fix: invalid input, a refused payment, a missing record.

```ts

if (typeof input?.amount !== "number") {
  throw new TerminalError("amount must be a number", 400);
}
```

- `code` defaults to `500`. Use HTTP-style codes; the code and message reach the caller. A code
  that is not an integer from 0 to 2³²−1 becomes `500`.
- A caller using `/invoke` gets `500` with `{"status": "failed", "code": 400, "message": ...}`; the
  [typed client](/docs/develop/client) throws `InvocationFailed`, which is itself a `TerminalError`.
- A handler that called the failed one with `ctx.call` gets a `TerminalError` with the same code
  and message.
- You can catch a `TerminalError` and carry on — that is how you write compensation (sagas).
- Thrown inside a `ctx.run` closure, it becomes the step's recorded result: the closure does not
  run again, and `ctx.run` throws the same error on every replay.

## Retried errors

Any error that is not a `TerminalError` or `PauseError` fails the current **turn**. Cairnflow
schedules another attempt with backoff. On the next attempt, steps already in the journal return
their recorded results; only the work that did not finish runs again.

Inside a `ctx.run` closure the rule is strict: once a closure throws a normal error, the turn is
dead even if your code catches the error. The next `ctx` command throws `TurnFailed`, and the turn
ends as a failure to retry. Continuing past the error would let later steps depend on a result the
retry is about to replace. If you want a step's failure recorded so it never runs again, throw
`RunFailure` or `TerminalError` from the closure — see [Durable steps](/docs/develop/durable-steps#errors-inside-a-step).

### Retry policy

Without a policy, retries are unlimited with backoff starting at 100 ms, doubling, capped at
60 seconds. Set a policy per service or per handler:

```ts
service("Payments", { charge }, {
  options: {
    retryPolicy: {
      initialInterval: 200,
      maxInterval: 30_000,
      exponentiationFactor: 2,
      maxAttempts: 5,
      onMaxAttempts: "PAUSE",
    },
  },
});
```

| Field | Default | Meaning |
|---|---|---|
| `initialInterval` | `100` | First backoff, ms |
| `maxInterval` | `60000` | Largest backoff, ms |
| `exponentiationFactor` | `2` | Multiplier between attempts; must be at least 1 |
| `maxAttempts` | unlimited | Total attempts **including the first**; at least 1 |
| `onMaxAttempts` | `"PAUSE"` | `"PAUSE"` keeps the invocation for an operator; `"KILL"` ends it as `failed` |

When attempts run out, the invocation ends `paused` (or `failed` with `KILL`) with code `575`, and
the message includes the last attempt's error. `POST /invocations/{id}/resume` gives a paused
invocation another round of attempts.

The policy is captured when the deployment is registered; changing it means registering a new
deployment.

### Giving up on purpose

`ctx.attempt` counts the attempts since the handler last made progress: `0` on a first run, and it
resets every time the journal grows. Use it to stop retrying a dependency that is down for good:

```ts

const result = await ctx.run("call vendor", async () => {
  if (ctx.attempt >= 3) {
    throw new RunFailure("vendor did not answer after 3 attempts", 503);
  }
  return callVendor();
});
```

## Paused invocations

An invocation is `paused` when it cannot continue without a person:

| Code | Cause | What to do |
|---|---|---|
| `570` | Journal mismatch: the code no longer matches the recorded steps | Fix the code or move the invocation — see [Deploying new versions](/docs/develop/versioning) |
| `575` | Retry attempts exhausted | Fix the cause, then resume |
| your code | You threw `PauseError` | Fix the cause, then resume |

Throw `PauseError` for problems that will not fix themselves but are worth keeping the work for —
stock that must be restocked, a quota that must be raised:

```ts

const inStock = await ctx.run("check stock", () => stock.count(sku));
if (inStock < input.quantity) {
  throw new PauseError(`missing ${input.quantity - inStock} of ${sku}`);
}
```

`POST /invocations/{id}/resume` continues the invocation from where it stopped. The answer carries
the status after continuing: it can complete, suspend, or pause again if nothing changed.

:::caution
A paused invocation on a virtual object **keeps its place in the key's exclusive queue**. Other
exclusive invocations on that key wait until it is resumed, cancelled or finished.
:::

A caller waiting with `/invoke` gets `409` with `{"status": "paused", "code": ..., "message": ...}`;
the typed client throws `InvocationPaused`.

## Don't swallow control flow

When your code awaits something that is not ready yet (a timer, a call, a signal, a step result
not yet durable), the promise simply stays pending until the turn ends; nothing is thrown. The SDK
throws its own errors only in a few cases, and none of them is an error of your code:

| Error | When |
|---|---|
| `TurnFailed` | A `ctx` command after a step's closure threw a normal error; the turn will be retried |
| `JournalMismatch` | A command does not match the journal; the invocation pauses with `570` |
| `Suspend` | A `ctx` command after the turn has already suspended, for example from code still running after it awaited something outside the SDK |

Catching them changes nothing: the turn still suspends, fails or pauses. If you need a broad
`catch`, rethrow them:

```ts

try {
  await doWork(ctx);
} catch (e) {
  if (e instanceof Suspend || e instanceof TurnFailed || e instanceof JournalMismatch) throw e;
  // handle your own errors here
}
```

For the full list of failure codes, see [Errors reference](/docs/reference/errors).
