# Errors and debugging

> Read when something throws or reruns unexpectedly. Know which errors reach the caller and which go to onError, find why a value recomputed with inspect, and tell errors apart.

## Example

`Source.inspect` reports what a value read and why it last recomputed.

```ts
import { Realm, Source } from "@frondruntime/sorus";
import { app } from "./realm.ts";
import { $canSend, typeText } from "./state.ts";

const inspectCanSend = () => {
  const stop = Realm.watch(
    app,
    (read) => read($canSend),
    () => undefined,
  );
  typeText("hi");
  const inspected = Source.inspect($canSend);
  // { name: "canSend", realm: "app", dependencies: ["composer", "connection"],
  //   observers: 1, lastReason: "composer changed", stages: [] }
  stop();
  return inspected;
};
```

Every error Sorus throws is a `SorusError`, told apart by its `_tag`.

```ts
import { isSorusError } from "@frondruntime/sorus";

// What the chat's error reporter files an error under.
const kindOf = (error: unknown): string => {
  // A misuse, a bug in the caller: its code names which.
  if (isSorusError(error, "SorusUsageError")) return error.code;
  // A condition code handles, such as "StageConflictError".
  if (isSorusError(error)) return error._tag;
  return "other";
};
```

## Rules

- An error with a caller throws to it, and an update that throws is undone:
  every check runs in every build, since Sorus has no development mode.
- An error with no caller goes to `onError` ([Realms](../state/realms.md)): a
  watch effect's, an autorun's after its first run, a hook's, a `Realm.onUpdate`
  listener's. The write has landed; the first run of a watch or autorun throws
  to the caller.
- Name what gets debugged with `{ name }` on a box or a computed value: a
  named computed value keeps why it last recomputed, and its errors name it.
- Match an error by `isSorusError`, never by `instanceof`, which fails across
  two copies of Sorus, or by message text, which changes with the API.

## Answers

| Call | Answers |
| --- | --- |
| `Source.inspect($x)` | `{ name, realm, dependencies, observers, lastReason, stages }`, one level deep. `lastReason` is `undefined` unless the value is a named computed value that has run. |
| `isSorusError(error, tag?)` | Whether `error` is a `SorusError`; with `tag`, whether it is that error, narrowed to its class. |

## With Effect

A schema adds `ValueRejectedError` and `DecodeError`, each with the
`Schema.SchemaError` as `cause`: see [Schema-checked boxes](../effect/boxes.md).
A program's defect is logged, not thrown: see [Programs](../effect/programs.md).

## See also

- [Error messages](../reference/errors.md): every message, its cause, and the fix.
- [Updates](../state/updates.md): what an update undoes when it throws.
- [Reacting](../state/reacting.md): watch and autorun, and their first run.
- [Testing](./testing.md): asserting on a rejected write.
