Files
clawmates/skills/rust/rust-error-handling.md
T
Omar SobhandClaude Opus 4.7 7b23f61632
ci / gates (push) Successful in 4s
ci / frontend (push) Successful in 25s
ci / rust (push) Failing after 3m41s
ci / e2e (push) Skipped
ci / publish (push) Skipped
slice 3.5c: seed 15 built-in skills across the 6 stacks
Hand-authored skill catalog anchored to real 2026-07 versions:
  - Rust 1.97.1 (stable), edition 2024
  - React 19.2.7, Server Components + Actions
  - TailwindCSS 4.3.3 (CSS-first config, Oxide engine)
  - three.js r185 (WebGPURenderer stable, BatchedMesh matured)
  - React Native 0.86 / Expo SDK 54+ (New Architecture default)
  - cargo-nextest 0.9.140, gitleaks 8.20+, cargo-audit 0.21+
  - Postgres 17 (18 in beta, don't rely on)
  - CUDA Blackwell, Metal Apple7+, ROCm CDNA3

Ships 15 skills across the categories:
  foundation/  workspace-repo-commit-protocol
               small-focused-commits
               tdd-red-green-refactor
               code-review-checklist
               int-xx-marker-protocol
               decompose-int-items
  rust/        write-rust-current-edition
               rust-error-handling
               cargo-test-driven-development
               rust-async-tokio-idioms
  backend/     postgres-migrations-forward-only
               postgres-index-selection
               api-pagination-day-1
  frontend/    react-19-server-components
               tailwind-v4-idioms
               component-4-state-model
  mobile/      expo-managed-vs-bare
               rn-flashlist-perf
  gpu/         gpu-coalescing-and-occupancy
               roofline-model
  threejs/     threejs-perf-and-teardown
  security/    cargo-audit-workflow
               secret-scanning-gitleaks

skills_loader.rs walks skills/**/*.md, parses YAML frontmatter
(name, description, when_to_use, tags), upserts via
skills_catalog::upsert_builtin. Idempotent per boot — bumps version
+ appends skill_versions row ONLY when body changes. Deterministic
sha256-derived ids so builtins are stable across boots.

Dockerfile copies skills/ to /etc/clawmates/skills. Server boot
task spawns loader alongside team_template_loader.

Follow-ups (Slice 3.5c continuation, future PRs):
  - 20-30 more skills (duckdb, shadcn composition, a11y, WebGPU
    migration, metal frame capture, rocprof, deep gitea forge
    integration, semgrep rulepacks)
  - Bind skills to team template roles (add [role.skills] refs to
    templates/teams/*.toml + wire template_role_skills population
    in team_template_loader)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-07-19 13:55:44 -07:00

68 lines
2.5 KiB
Markdown

---
name: rust-error-handling
description: When to use `anyhow` vs `thiserror`, how to add context, when to panic. Rust 1.97+ idioms.
when_to_use: Any time you write a fn returning `Result` in Rust.
tags: [rust, errors]
---
# Rust error handling
## Which error type
- **Application binary** (`clawmates-server`, `clawmates-node`) → `anyhow::Result<T>` everywhere. You never match on the error at runtime; you print + log + exit.
- **Library crate** (`cm-db`, `cm-api`, `cm-runtime`) → `thiserror` on a per-module `Error` enum. Callers get typed variants they can match.
- **Test code** → `anyhow` is fine even in library crates. Tests don't match on error types.
## `thiserror` shape
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DbError {
#[error("row not found")]
NotFound,
#[error("workspace mismatch: expected {expected}, got {actual}")]
WorkspaceMismatch { expected: Uuid, actual: Uuid },
#[error(transparent)]
Sqlx(#[from] sqlx::Error),
}
```
Rules:
- **`#[from]` for exactly one wrapped external type per variant.** Otherwise `?` becomes ambiguous.
- **`#[error("...")]` includes the values.** Never `#[error("db error")]` — that's information-lossy.
- **`#[error(transparent)]`** for pass-through wrappers where the inner error's message is already sufficient.
## Adding context
Every `?` at a module boundary needs context. Without it, a deeply-nested `sqlx::Error` is unattributable.
```rust
use anyhow::Context;
let user = load(pool, id)
.await
.with_context(|| format!("load user {id}"))?;
```
- **`.context("...")`** for a static string.
- **`.with_context(|| ...)`** when the message includes runtime data (allocation is lazy — only fires on error).
## When to panic
Panic is fine when:
- The invariant CAN'T be violated at runtime (`unreachable!("mission_kind is validated at insert time")`).
- You're in `main()` before the async runtime, and the config file is broken — `.expect("clawmates.toml is required")`.
- Test-only preconditions (`assert_eq!` inside `#[test]`).
Panic is NOT fine when:
- The input came from the network.
- The input came from a config parse.
- The input came from a database row that a migration is supposed to guarantee — write an `Error` variant explaining WHY the row shape violates the invariant.
## Backtrace hygiene
- Set `RUST_BACKTRACE=1` in dev + CI. Off in prod (leaks internals).
- `anyhow::Error` captures a backtrace automatically. Log it via `error!("op failed: {e:?}")` — the `?` formatter includes the chain + backtrace.