error-concept

Typed library errors and application context

Keep stable recovery variants in library functions, then add task-level context when calling them from an application. This lets users diagnose a failure without replacing its type. Requires thiserror = "=2.0.12"; anyhow = "=1.0.104" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): reserve cart item; known=true Expected stderr: (empty) Expected exit: success Common mistake: Using anyhow in every public library signature even when callers need documented variants.

Formal Syntax & Structure

rust syntaxrust
library: Result<T, DomainError>; application: anyhow::Result<T>

Working Example

Example Snippetrust
use anyhow::Context;#[derive(Debug, thiserror::Error)]#[error("item unavailable")]struct Unavailable;fn reserve() -> Result<(), Unavailable> { Err(Unavailable) }fn main() {    if let Err(e) = reserve().context("reserve cart item") {        println!("{e}; known={}", e.is::<Unavailable>());    }}
Rust Reference