Hasty Briefsbeta

Trying to get error backtraces in Rust libraries right

15 days ago
  • #Error Handling
  • #Rust
  • #Backtraces
  • Rust error handling is divided into two main approaches: `anyhow` for generic errors with backtraces and `thiserror` for precise enum-based errors.
  • The standard library's IO error model offers a third approach, splitting errors into kind and source for both high-level matching and detailed context.
  • Backtrace propagation in Rust is unstable, causing issues with nested errors and requiring trade-offs between ergonomics and backtrace support.
  • `snafu` is a hybrid solution combining `thiserror`'s enum-based errors with backtrace capture and context attachment, addressing some limitations.
  • The `iroh` project uses `snafu` for structured errors in public APIs while preserving debugging info, with `n0-snafu` for ergonomic test writing.
  • Guidelines for error handling include scoping enums to functions, using descriptive names, and providing custom variants for public traits.
  • Trade-offs exist: structured errors require more upfront work but offer stable APIs, while generic errors are quicker to implement.
  • The Rust community encourages structured errors for libraries, but pragmatic choices should prioritize project needs over dogma.