---
stage: errors
requires:
  - api
  - models
  - config
  - dependencies
  - decisions
outputs: "{wiki_dir}/errors.md"
version: 2.1.0
estimated_tokens: 2000

guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Delete any files"
    - "Modify any source files"
  read_only: true
---
# Stage 13: Error Handling Documentation

Generate documentation of error handling patterns, error types, and troubleshooting guides.

## Prerequisites

- Stage 12 completed with decisions.md generated
- Mode: `{REPOIX_MODE}` (if "cli", convert MCP calls per AGENTS.md)
- Discovery cache loaded: LIMITS, PRIMARY_LANGUAGE

## Critical Rules

| Rule | Action |
|------|--------|
| Decisions required | **MUST** verify {wiki_dir}/architecture/decisions.md exists |
| Analyze code | **NEVER** document without analyzing actual code |
| Mermaid only | **MUST** use Mermaid class diagrams (no ASCII) |
| Skip if none | **MAY** skip if no error handling patterns found |

---

{{include:ai-cache-enforcement.md}}

{{include:understand-fast-path.md}}

---

**Anti-pattern (DO NOT):**

```text
BaseError
    +-- ValidationError
    +-- NotFoundError
```

**Correct pattern:**

```mermaid
classDiagram
    BaseError <|-- ValidationError
    BaseError <|-- NotFoundError
```

---

## Step 1: Verify Previous Stage

```bash
civyk-hatch deepwiki-update-state verify-stage --stage=13-errors --wiki-dir={wiki_dir}
```

---

## Step 2: Load Discovery Cache

```bash
civyk-hatch deepwiki-update-state show --wiki-dir={wiki_dir}
# Extract: LIMITS = discovery_cache.project_size.limits
# Extract: PRIMARY_LANGUAGE = discovery_cache.file_patterns.languages.primary
```

**MCP/CLI conversion (if REPOIX_MODE == "cli"):**

| MCP Call | CLI Equivalent |
|----------|----------------|
| `search(action="symbols", query="%Error", kind="class")` | `civyk-repoix query search --action symbols --query "%Error" --kind class` |
| `symbol(action="hierarchy", fqn="...", direction="both")` | `civyk-repoix query symbol --action hierarchy --fqn "..." --direction both` |
| `search(action="code", query="throw|raise", is_regex=true)` | `civyk-repoix query search --action code --query "throw|raise" --is-regex true` |

---

## Step 3: Search Error Patterns

```text
# Error throwing/raising
search(action="code", query="throw|raise", is_regex=true, limit=200)
search(action="code", query="Error|Exception", is_regex=true, limit=200)
search(action="code", query="log.error|logger.error|console.error", is_regex=true, limit=100)

# Error classes
search(action="symbols", query="%Error", kind="class", limit=100)
search(action="symbols", query="%Exception", kind="class", limit=100)

# Try-catch patterns
search(action="code", query="try|catch|except|finally", is_regex=true, limit=200)

# Language-specific
# Go: search(action="code", query="if err != nil|errors.New", is_regex=true, limit=100)
# Rust: search(action="code", query="#\\[error|anyhow::", is_regex=true, limit=50)
# Result/Either: search(action="code", query="Result<|Either<|Ok\\(|Err\\(", is_regex=true, limit=50)
```

---

## Step 4: Analyze Error Classes

For each error class:

```text
# Get type hierarchy
symbol(action="hierarchy", fqn="<base_error>", direction="both", depth=5)

# Find similar errors and duplicate handling patterns
symbol(action="similar", fqn="<error_class>", similarity_threshold=0.6, limit=30)
quality(action="duplicates", source_only=true, similarity_threshold=0.6, limit=30)

# Get symbol details
symbol(action="detail", fqn="<error_class>")

# Find references
symbol(action="references", fqn="<error_class>")

# Get callers
symbol(action="callers", fqn="<throwing_method>", depth=3)

# Read implementation
# Read file: <error_class_file>
# -> Extract error message templates
# -> Note error codes
# -> Understand context

# Find tests
file(action="related", path="<error_file>", relationship_types=["test"])
```

---

## Step 5: Generate Documentation

**[!] CRITICAL OUTPUT FILE: You MUST write to `{wiki_dir}/errors.md`**

- Do NOT create `issues.md`, `error-handling.md`, or any other filename
- The output MUST be exactly: `{wiki_dir}/errors.md`

Write `{wiki_dir}/errors.md` using this template:

{{include:wiki/errors-template.md}}

**Fill placeholders with:** Error handling summary, Mermaid error hierarchy diagram, error types table, centralized handler patterns, logging levels table, retryable errors table, troubleshooting guide.

---

## Step 6: Complete Stage

```bash
civyk-hatch deepwiki-update-state stage --stage=13-errors --status=completed --artifacts="{wiki_dir}/errors.md" --wiki-dir={wiki_dir}
```

---

## Output Format

```text
===========================================================
  STAGE COMPLETE: 13-errors

  Generated: {wiki_dir}/errors.md
  Error classes: {count}
  Error patterns: {count}

  Next: Run {next_command}
===========================================================
```

---

## Edge Cases

| Scenario | Action |
|----------|--------|
| No custom error classes | Document standard error patterns |
| External error codes | Link to external documentation |
| Multiple error patterns | Document each separately |
| Logging-based errors | Focus on log patterns |

---

## Next Stage

Run `{next_command}` - CLI auto-detects current stage and emits next prompt.
