# Error Handling
Source: https://docs.maelstrom-ai.co/dev/guides/react/error-handling/
Documentation revision: 89a8f5e9d10cedcf0b30376d7846113f06f26120
SDK manifests in this build: @maelstrom-co/react@0.2.1, @maelstrom-co/client@0.2.1, @maelstrom-co/connectors@0.2.1, @maelstrom-co/protocol@0.2.1, @maelstrom-co/engine@0.2.1
These docs follow this source revision. Manifest versions do not prove release compatibility; verify the installed package exports before using an API.

Maelstrom surfaces failures through a small, deliberate set of channels. This guide shows you where each kind of error lands and how to build UI around it.

Use [DevTools](https://docs.maelstrom-ai.co/dev/guides/devtools/) to inspect the failing request before changing its error handling. **Requests** separates response receipt, layout application, and failed or skipped Actions. **Connections** shows transport evidence. Start a recording before reproducing a problem when supported content is needed; automatic activity contains metadata only.

> [!TIP]
> Use with a coding agent
> 
> To investigate a concrete issue, use the [Maelstrom debugging prompt](https://docs.maelstrom-ai.co/agents/prompts/maelstrom-debugging/) with the symptom and redacted evidence. It is for diagnosis from repository and runtime evidence before changing code; it does not authorize a fix by itself. For narrowly scoped event reporting, use the [observability prompt](https://docs.maelstrom-ai.co/agents/prompts/maelstrom-observability/); it requires event and payload evidence from the installed SDK.
> 
> Debug a Maelstrom issue
> 
> ```
> 
> Diagnose this Maelstrom issue from repository and runtime evidence before changing
> code.
> 
> Repository root: [PATH]
> Symptom: [DESCRIPTION]
> Redacted error/log output: [OUTPUT]
> Relevant files: [PATHS OR "discover"]
> 
> Inspect package manifests and lockfile for exact installed Maelstrom package
> versions. Read the relevant code, tests, and those versions' source/types/docs.
> Never assume an API based on a different release. Do not request or print provider
> credentials, session tokens, or unredacted user data.
> 
> ## Classify the failure surface
> 
> Use observed evidence to classify one or more relevant surfaces:
> 
> - Engine or intent processing;
> - Connector or transport;
> - Vessel rendering or lazy loading;
> - Vessel definition/state-machine validation;
> - Action handler or transition;
> - layout or definition/update synchronization.
> 
> Inspect the evidence relevant to the symptom: `m.useMaelstrom()` state, including
> `connectionStatus`, `connectionError`, `isProcessing`, `lastError`, and
> `lastResponse` where available; Provider `onError`; browser Connector state;
> server Engine logs; current Vessel definition and active Variant; Action
> parameters/transitions; relevant events; and installed-version compatibility.
> 
> When DevTools is installed, inspect its retained metadata before adding custom
> listeners. Load the guide shipped by the installed `@maelstrom-co/react-devtools`
> or `@maelstrom-co/devtools` package and verify its exports. Requests separates
> response receipt, application, and Action outcomes; identify each request by app
> lifetime and request ID. Connections shows Engine and optional voice evidence.
> In All events, search for `voice.` to isolate voice metadata.
> 
> Record supported content only when the user's authorization covers retaining
> application data. Choose a scope and start recording before reproduction, then
> stop and inspect it. Inspection filters do not change that scope. Inspect and
> redact any export before sharing it. Imported recordings are read-only evidence,
> not replay. Missing Engine stages can mean forwarding is unavailable. Use existing
> state and logs when DevTools is absent; a diagnosis does not authorize installation,
> production browser opt-in, or server forwarding changes.
> 
> Do not assume `processIntent()` rejects on failure. Inspect Maelstrom state and
> error reporting. Do not diagnose a connector failure as Vessel logic without
> linking evidence. Do not suppress validation or type errors with casts. Distinguish
> observations from hypotheses; missing evidence means the root cause remains
> unconfirmed.
> 
> ## Change only when authorized
> 
> Requested authority: [DIAGNOSE ONLY | IMPLEMENT A FIX]
> 
> For diagnose-only requests, make no edits and stop after a bounded evidence-based
> report and verification suggestions. If implementation is explicitly authorized,
> inspect first, then apply only the smallest fix supported by evidence. Do not
> rewrite unrelated Vessel logic, change Engine prompts by default, or add inline
> layout reconciliation. Preserve client ownership of layout. For update conflicts,
> inspect whether the Vessel is factory-declared or runtime-registered and use its
> supported update path; handle conflicts explicitly rather than discarding them.
> 
> ## Verify and report
> 
> Run focused existing tests and relevant project checks for any authorized change.
> For diagnosis without edits, run only checks that can add useful evidence and state
> which checks were not run. Redact secrets and user content from recorded evidence.
> 
> Return:
> 1. failure-surface classification and observed evidence;
> 2. confirmed root cause or clearly labeled alternatives and missing evidence;
> 3. minimal patch only if authorized;
> 4. checks performed with exact outcomes;
> 5. residual risk and the next evidence or action needed.
> ```
> Add focused event observability
> 
> ```
> 
> Add focused observability to this Maelstrom integration.
> 
> Question or operational goal: [GOAL]
> Telemetry conventions: [SYSTEM OR "inspect"]
> Relevant integration paths: [PATHS OR "discover"]
> Implementation authorized: [YES / NO]
> 
> For a local inspection goal, check existing DevTools metadata before adding
> custom listeners. Verify the installed DevTools version and its package-owned
> guide. Content recording requires authorization to retain application data.
> Keep operational reporting in the application's telemetry system; DevTools
> provides local inspection and explicit recordings.
> 
> Inspect package versions and the current integration before changing code. Find
> the event types and payloads in the installed SDK exports, declarations, source,
> tests, or matching API docs. Trace how listeners are registered and disposed.
> Subscribe only to concrete supported events needed to answer the goal. Candidate
> surfaces in the current client include connection status/attempt/error events,
> request processing start/completion, coalesced update flushes, and Vessel
> registration; verify the chosen names and payload fields against this checkout
> before using them. Do not assume every object exposes every event.
> 
> Keep reporting separate from product state and Connector transport. Prefer a
> small event-to-metric/log mapping with stable identifiers only when already
> provided. Do not log credentials, authorization headers, prompt/intent contents,
> Vessel props, user data, or raw errors that may contain them by default. Define
> redaction and retention using the application's existing telemetry conventions.
> Dispose subscriptions with their owner; do not add a parallel state store or
> high-cardinality labels without evidence and a reason.
> 
> If authorized, implement only the requested bounded instrumentation after
> inspection. Add deterministic tests for event mapping, redaction, and cleanup
> where applicable. Run affected typecheck, tests, and check. Report exact source
> anchors, files, commands and results; distinguish local test evidence from live
> telemetry delivery. If no suitable supported event exists, report the gap rather
> than inventing an SDK event.
> 
> Return the selected events and why, event-to-signal mapping, privacy choices,
> lifecycle cleanup, test evidence, and unverified deployment work.
> ```

> [!NOTE]
> Note
> 
> **Before you start:** this guide builds on the `greetingVessel` and `<m.Provider connector={...}>` setup from [Creating Vessels](https://docs.maelstrom-ai.co/dev/guides/react/creating-vessels/). The React package surfaces plain `Error` objects; there is no public error-type taxonomy to match on, so handle errors by _where_ they come from, not by class.

## The three failure surfaces

Frame your handling around where the failure originates. Each surface has a distinct channel:

| Surface | Channel | What it covers |
| --- | --- | --- |
| [Engine / processing](https://docs.maelstrom-ai.co/dev/understanding/engine/) | `useMaelstrom().lastError` (plus `onError`) | A `processIntent` call fails: the engine rejects, the request times out, or response handling throws. |
| [Connector](https://docs.maelstrom-ai.co/dev/understanding/connectors/) | `useMaelstrom().connectionStatus` + `connectionError` (plus `onError` on initial connect) | The transport fails to connect or the Orchestrator fails to start. Mid-session drops update `connectionStatus`/`connectionError` only; they do not reach `onError`. |
| [Vessel runtime](https://docs.maelstrom-ai.co/dev/understanding/vessel-state-machine/) | The built-in `ErrorBoundary` | A _lazy_ vessel’s render throws or its chunk fails to load. Eagerly registered vessels rely on your own React error boundary. |

The first two are reactive state you read in your own components. The third is automatic and internal, covered below.

## Catching engine and connector errors

Two entry points cover both surfaces.

### The Provider `onError` callback

`<m.Provider>` accepts an `onError` prop that fires for connection failures, Orchestrator startup failures, `processIntent` failures, and failed `executeAction` calls. It receives a single `Error`:

src/app.tsx

```tsx
import { m } from './maelstrom';
import { myConnector } from './connector';

export default function App() {
  return (
    <m.Provider
      connector={myConnector}
      onError={(error) => {
        // error is always a plain Error. Log it, report to telemetry, etc.
        console.error('[Maelstrom]', error);
      }}
    >
      <m.Chart />
    </m.Provider>
  );
}
```

`onError` is the right place for side effects: logging, toasts, error reporting. It is not where you render fallback UI; for that, read the state with `useMaelstrom()`.

> [!TIP]
> Tip
> 
> Every error passed to `onError` _also_ surfaces through `useMaelstrom()`. Use `onError` for fire-and-forget side effects and the hook for anything you render. You don’t have to choose one.

### Reading error state with `useMaelstrom()`

`useMaelstrom()` exposes the reactive error state you render against:

| Field | Type | Description |
| --- | --- | --- |
| `lastError` | <code>Error &#124; null</code> | The last error from `processIntent`. Auto-clears on the next call. |
| `connectionStatus` | `ConnectionStatus` | One of `'disconnected'`, `'connecting'`, `'connected'`, `'error'`. |
| `connectionError` | <code>Error &#124; null</code> | The last connection error, set when `connectionStatus` is `'error'`. |

`processIntent` never rejects; it always resolves, and a failure shows up as a populated `lastError` instead. So you don’t need a `try/catch` around the call; read `lastError` afterwards.

src/components/intent-bar.tsx

```tsx
import { useState } from 'react';
import { m } from '../maelstrom';

export default function IntentBar() {
  const { processIntent, isProcessing, lastError, connectionStatus, connectionError } =
    m.useMaelstrom();
  const [intent, setIntent] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!intent.trim() || isProcessing) return;
    // processIntent never rejects; inspect lastError after it resolves.
    await processIntent(intent);
    setIntent('');
  };

  return (
    <div>
      {connectionStatus === 'error' && (
        <div role="alert">
          Lost connection to the engine.
          {connectionError && <span> {connectionError.message}</span>}
        </div>
      )}

      {lastError && (
        <div role="alert">Couldn't process that: {lastError.message}</div>
      )}

      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={intent}
          onChange={(e) => setIntent(e.target.value)}
          disabled={isProcessing || connectionStatus !== 'connected'}
        />
        <button type="submit" disabled={isProcessing || !intent.trim()}>
          {isProcessing ? 'Working...' : 'Send'}
        </button>
      </form>
    </div>
  );
}
```

Gate input on `connectionStatus === 'connected'` so users aren’t typing into a dead session, and use `connectionStatus` (not just `connectionError`) to drive the banner, since `'connecting'` is a normal transient state, not a failure.

## Vessel runtime errors

Rendering a vessel can throw errors. Maelstrom catches them so one broken vessel can’t take down the whole Chart.

This is **automatic and internal**: there is nothing to wire up, and almost nothing to configure:

-   The Chart wraps each **lazy** vessel in a built-in `ErrorBoundary`. If a lazy component’s chunk fails to load or its render throws, the boundary catches it.
-   The fallback is a built-in error card (`VesselLoadError`) showing “Failed to load” plus a **Retry** button. Retry works by incrementing an internal key, which produces a fresh `React.lazy()` instance and re-attempts the import.
-   The same caught error is forwarded to your Provider `onError` callback, so you still get to log or report it.

> [!WARNING]
> Caution
> 
> The `ErrorBoundary` and its fallback card are **not exported** and the Chart wires them only around **lazy** vessels; eagerly registered (non-lazy) vessels render without a boundary, so a throw there propagates to your own nearest React error boundary. The only knobs you control are the Provider `onError` callback and the per-vessel loading component (see [Lazy Loading](https://docs.maelstrom-ai.co/dev/guides/react/lazy-loading/)). The fallback card markup, the retry mechanism, and the boundary placement are all internal. If you need a custom error card for a non-lazy vessel, add your own React error boundary around it.

## Retry UX

There is no single global “retry”, recovery is per-surface:

-   **Connector errors.** When `connectionStatus === 'error'`, recovery depends on your connector’s reconnect behavior. Surface the `'error'` state in your UI and give the user a way to retry the action once status returns to `'connected'`.
-   **Lazy vessel loads.** The built-in `VesselLoadError` card already renders a **Retry** button that re-imports the failed chunk. You get this for free; see [Lazy Loading](https://docs.maelstrom-ai.co/dev/guides/react/lazy-loading/) for how lazy entries are registered.
-   **Failed intents.** Because `lastError` auto-clears on the next `processIntent` call, the simplest user-facing affordance is letting the user resubmit, since the stale error clears itself on the retry.

The throughline: keep a working input path visible whenever an error is on screen, so the user always has a way forward.

## Recovery decision tree

```mermaid
flowchart TD
  Failure["Failure appears"]
  Connection{"connectionStatus<br/>is error?"}
  LastError{"lastError<br/>is set?"}
  LazyFallback{"Lazy vessel fallback<br/>appears?"}
  Disconnected["Show disconnected state,<br/>wait for reconnect,<br/>keep retry visible"]
  Resubmit["Let the user edit<br/>or resubmit the intent"]
  Retry["Use built-in Retry card<br/>or report through onError"]

  Failure --> Connection
  Connection -->|"yes"| Disconnected
  Connection -->|"no"| LastError
  LastError -->|"yes"| Resubmit
  LastError -->|"no"| LazyFallback
  LazyFallback -->|"yes"| Retry
```

The useful rule is to keep a working input path visible. Users should never have to refresh the page just to recover from a failed intent or transient connector issue.

Reference surfaces: [`MaelstromProviderProps`](https://docs.maelstrom-ai.co/dev/reference/react/type-aliases/maelstromproviderprops/), [`MaelstromState`](https://docs.maelstrom-ai.co/dev/reference/react/interfaces/maelstromstate/), and [`DynamicVesselHandle`](https://docs.maelstrom-ai.co/dev/reference/react/interfaces/dynamicvesselhandle/).

## Next steps

-   [Lazy Loading Vessels](https://docs.maelstrom-ai.co/dev/guides/react/lazy-loading/) — register lazy vessels and customize their loading and error states
-   [Creating Vessels](https://docs.maelstrom-ai.co/dev/guides/react/creating-vessels/) — the `greetingVessel` setup this guide builds on
-   [The Engine](https://docs.maelstrom-ai.co/dev/understanding/engine/) — how the engine validates and heals responses, the source of many processing errors
