> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Errors and Diagnostics

The library emits two kinds of signals:

- **Errors** (`Error`) stop the current call and are thrown; the caller must handle them.
- **Diagnostics** (`WikitextDiagnostic`) record a local problem or degradation on the snapshot without aborting the page.

## Error classes

```ts
class WikitextError extends Error {
  readonly code: WikitextErrorCode;
  cause?: unknown;
}

class WikitextParseError extends WikitextError {}

class WikitextPrepareError extends WikitextError {
  readonly stage: string;
}

class WikitextExpandError extends WikitextError {
  readonly templateTitle?: string;
  readonly range?: WikitextRange;
}
```

Every error carries `code`; `cause` keeps the underlying error. `WikitextPrepareError.stage` records the failing stage, commonly `prepare`, `wikitext`, `rehype`, or `finalize`.

## Exports by entry

| Entry            | Error exports                                                     |
| ---------------- | ----------------------------------------------------------------- |
| `/ast`, `/parse` | `WikitextError`, `WikitextParseError`, `WikitextErrorCode`        |
| `/hast`          | `WikitextError`, `WikitextPrepareError`                           |
| `/expand`        | `WikitextError`, `WikitextExpandError`, `WikitextExpandErrorCode` |
| Root, `/view`    | No error classes; render failures are handled by error boundaries |

## Error codes

| Code                        | Stage           | Trigger                                                 |
| --------------------------- | --------------- | ------------------------------------------------------- |
| `SOURCE_TOO_LONG`           | Parse           | Normalized source exceeds the length budget             |
| `SOURCE_TOO_COMPLEX`        | Parse           | Syntax or semantic tree exceeds node/depth budget       |
| `INVALID_CONFIG`            | Parse           | Site config or budget field is invalid                  |
| `PARSE_FAILED`              | Parse           | Upstream parsing or semantic building failed            |
| `PARSER_UNAVAILABLE`        | Parse           | Default browser bundle did not initialize               |
| `PREPARE_FAILED`            | Prepare         | Options, plugin, handler, or budget check failed        |
| `ASYNC_PLUGIN_IN_SYNC_PATH` | Prepare         | Async plugin on the sync path                           |
| `INVALID_DOCUMENT`          | Restore/Prepare | Snapshot structure, version, root, or budget is invalid |
| `INVALID_EXPAND_OPTIONS`    | Expand          | Expansion options are invalid                           |
| `INCOMPATIBLE_PARSER`       | Expand          | Injected parser cannot support expansion                |
| `TEMPLATE_NOT_FOUND`        | Expand          | Missing template under `strict`                         |
| `TEMPLATE_RESOLVE_FAILED`   | Expand          | Resolver failure under `strict`                         |
| `TEMPLATE_PARSE_FAILED`     | Expand          | Template source parse failure under `strict`            |
| `TEMPLATE_LOOP`             | Expand          | Loop detected under `strict`                            |
| `UNSUPPORTED_CALL`          | Expand          | Unsupported call under `strict`                         |
| `UNRESOLVED_DEPENDENCY`     | Expand          | Unresolved dependency under `strict`                    |
| `EXPANSION_BUDGET_EXCEEDED` | Expand          | Budget exceeded under `strict`                          |
| `EXPANSION_TOO_LARGE`       | Expand          | Expanded output or preserved source is too large        |
| `FINAL_PARSE_FAILED`        | Expand          | Final parse failure under `strict`                      |
| `ABORTED`                   | Expand          | Cancelled through `AbortSignal`                         |

In the default mode, expansion preserves calls and records diagnostics; with `strict: true`, recoverable failures above are thrown.

## Handling examples

```ts
import { WikitextParseError } from "react-wikitext/parse";

try {
  const document = parser.parse(source, { pageName: "Example" });
  return document;
} catch (error) {
  if (error instanceof WikitextParseError) {
    if (error.code === "SOURCE_TOO_LONG") {
      return loadSourceInPages(source);
    }
    throw error;
  }
  throw error;
}
```

```ts
import { prepareWikitextAsync, WikitextPrepareError } from "react-wikitext/hast";

try {
  return await prepareWikitextAsync(document, { rehypePlugins });
} catch (error) {
  if (error instanceof WikitextPrepareError) {
    report(error.code, error.stage, error.cause);
  }
  throw error;
}
```

- Never branch on `message` text; use `code` (and `stage` when relevant).
- Catch parse and prepare errors at the call site and distinguish budgets, config, and plugins.
- Report view failures through `onRenderError`; the error boundary replaces only the failed top-level block.
- Do not silently fall back to reparsing when restoring a snapshot fails; check the version and the source first.

## Diagnostics

```ts
interface WikitextDiagnostic {
  readonly code: string;
  readonly stage: "parse" | "expand" | "wikitext" | "hast" | "rehype" | "sanitize" | "finalize";
  readonly severity: "error" | "warning" | "info";
  readonly message: string;
  readonly position?: WikitextPosition;
  readonly origin?: WikitextOrigin;
  readonly rule?: string;
}
```

- `position` and `origin` refer to the normalized source; generated content may have no origin.
- `rule` identifies the rule or plugin that produced the record.
- Render snapshot diagnostics merge parse, preparation, and finalization records.
- A single diagnostic never aborts the page; the host decides whether to report or block.

## Related

- [Troubleshooting](/guide/troubleshooting.md): narrow down by symptom.
- [Preparation `/hast`](/api/prepare.md): prepare-stage and plugin errors.
- [Expansion `/expand`](/api/expand.md): `strict` mode and expansion errors.
