Every ERR rule the audits report, with the reason, a before/after fix, and when the pattern is acceptable. After that, smells the scripts cannot see. Examples use thiserror 2 and anyhow 1.
Contents
- ERR001-ERR003: panics in library code
- ERR004:
Box<dyn Error>withoutSend + Sync - ERR005: anyhow in a library API
- ERR006:
map_err(|_| ..) - ERR007: stringly
map_err - ERR008:
Result<T, String> - ERR009: source printed twice
- ERR010: exhaustive public error enums
- ERR011: discarded results
- ERR012:
?without context - ERR013:
process::exitinstead of returning - Smells the scripts cannot see
ERR001-ERR003: panics in library code
A library cannot know whether its caller can recover; panicking takes that decision away and loses the error value.
// Before
pub fn port(cfg: &HashMap<String, String>) -> u16 {
cfg.get("port").unwrap().parse().expect("port must be a number")
}
// After
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("missing key {0:?}")]
Missing(&'static str),
#[error("invalid value {value:?} for {key}")]
Invalid { key: &'static str, value: String, #[source] source: std::num::ParseIntError },
}
pub fn port(cfg: &HashMap<String, String>) -> Result<u16, ConfigError> {
let value = cfg.get("port").ok_or(ConfigError::Missing("port"))?;
value.parse().map_err(|source| ConfigError::Invalid { key: "port", value: value.clone(), source })
}Acceptable: expect for genuine invariants, phrased as the invariant (.expect("regex literal is valid"),
.expect("index < len checked above")); unwrap in tests, examples, build scripts and main of small tools.
Document deliberate panics under a # Panics heading. todo!/unimplemented! should not ship.
ERR004: Box<dyn Error> without Send + Sync
Box<dyn Error> cannot be sent to another thread or task, cannot be returned from a tokio::spawned future,
and does not convert into anyhow::Error (which requires Send + Sync + 'static).
// Before: pub fn load(p: &str) -> Result<String, Box<dyn std::error::Error>>
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub fn load(p: &str) -> Result<String, BoxError> {
Ok(std::fs::read_to_string(p)?)
}Acceptable: fn main() -> Result<(), Box<dyn Error>> in a small binary (the audits exempt main).
ERR005: anyhow in a library API
Callers of a library need to react to failures (retry on timeout, 404 on not-found). With anyhow::Error
they must downcast to guess what happened, and every new internal error becomes invisible API.
// Before
pub fn fetch(id: u64) -> anyhow::Result<Item> { .. }
// After: typed at the boundary, anyhow stays inside the binary
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FetchError {
#[error("item {0} not found")]
NotFound(u64),
#[error("request timed out")]
Timeout,
#[error("transport error")]
Transport(#[source] std::io::Error),
}
pub fn fetch(id: u64) -> Result<Item, FetchError> { .. }Acceptable: internal (pub(crate)) functions, workspace-internal crates owned by one binary, CLI-only crates.
ERR006: map_err(|_| ..)
The original error is thrown away: no source(), no cause in logs.
// Before
let n: usize = raw.parse().map_err(|_| StoreError::BadCount(raw.to_owned()))?;
// After: keep the cause
#[error("invalid count {input:?}")]
BadCount { input: String, #[source] source: std::num::ParseIntError },
let n: usize = raw.parse().map_err(|source| StoreError::BadCount { input: raw.to_owned(), source })?;Acceptable: when the source genuinely adds nothing and is huge or sensitive (rare); then say so in a comment.
ERR007: stringly map_err
e.to_string() or format!("..: {e}") keeps the message but loses the type, the chain and any backtrace.
// Before
fs::write(dest, json).map_err(|e| format!("write failed: {e}"))?;
// After (application code)
fs::write(&dest, json).with_context(|| format!("writing snapshot to {}", dest.display()))?;
// After (library code)
fs::write(&dest, json).map_err(|source| StoreError::Write { path: dest.to_owned(), source })?;ERR008: Result<T, String>
String errors cannot be matched, do not implement std::error::Error (no ? into anyhow, no source), and
push formatting into every call site.
- Library: a thiserror enum (generate one with
scaffold_errors). - Application:
anyhow::Result<T>withbail!("..")/.context(".."). Result<T, ()>: useOption<T>if there is only one failure, or a unit-variant enum.
ERR009: source printed twice
thiserror's Display comes from #[error(..)]; source() comes from the #[from]/#[source]/source field.
Reporters (anyhow's {:#}, {:?}, tracing with std::error::Error chains, eyre) print each layer's
Display and then walk source(), so a message that interpolates its own source prints it twice:
Error: i/o error: No such file or directory (os error 2)
Caused by:
No such file or directory (os error 2)// Before
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
// After: describe this layer only
#[error("i/o error on the store log")]
Io(#[from] std::io::Error),Use #[error(transparent)] when the wrapper adds nothing and should forward both Display and source().
ERR010: exhaustive public error enums
Adding a variant to an exhaustive public enum breaks every downstream match (a major release).
#[non_exhaustive] lets you add variants in minor releases; callers write a _ => arm. Inside the defining
crate, matches stay exhaustive.
ERR011: discarded results
let _ = f(); and f().ok(); silence the #[must_use] warning without handling the failure.
// Before
let _ = self.compact();
// After: decide explicitly
if let Err(e) = self.compact() {
tracing::warn!(error = %e, "compaction failed; continuing with an uncompacted log");
}Acceptable: best-effort cleanup where failure is expected and harmless (let _ = fs::remove_file(tmp); in a
Drop), ideally with a comment. Note let _ = x; drops x immediately, whereas let _guard = x; keeps it.
ERR012: ? without context
? on File::open produces No such file or directory (os error 2) with no path. In application code, add
what was being attempted:
let text = fs::read_to_string(&path)
.with_context(|| format!("reading config {}", path.display()))?;
let cfg: Config = serde_json::from_str(&text)
.with_context(|| format!("parsing config {}", path.display()))?;Use .context("static message") when nothing needs formatting; with_context avoids building the string on
success. In libraries, put the path in a variant field instead.
ERR013: process::exit instead of returning
std::process::exit does not run destructors (buffered writers are not flushed, temp files stay), cannot be
tested, and makes the function unusable as a library.
// Before
fn load_or_exit(path: &str) -> Store {
match Store::open(path) {
Ok(s) => s,
Err(e) => { eprintln!("cannot open store: {e}"); std::process::exit(1) }
}
}
// After
fn main() -> anyhow::Result<()> {
let store = Store::open(path).context("opening store")?; // main prints the chain, exits with 1
run(store)
}For custom exit codes return std::process::ExitCode from main (see anyhow-context-reporting.md).
Smells the scripts cannot see
| Smell | Why it hurts | Fix |
|---|---|---|
One giant crate-wide Error enum | every function "may return" every variant; callers cannot tell what to handle | one enum per module or operation family |
Variants named after dependencies (Reqwest(reqwest::Error)) in a public API | your semver is tied to theirs; callers depend on a crate they never chose | variants by meaning (Timeout, Transport), dependency error as #[source] |
| Logging and returning the same error at every layer | the same failure appears 5 times in logs | log once at the edge (handler, main, job runner) |
| Messages with capital letters and trailing periods | chains read "Failed to read. Caused by: Permission denied." | lowercase, no trailing punctuation: failed to read config |
Display that exposes secrets, SQL or user data | ends up in logs and HTTP bodies | keep sensitive data out of messages; map 5xx bodies to a generic text |
PartialEq derived on errors only for tests | blocks wrapping non-PartialEq sources | assert!(matches!(..)) in tests instead |
| Retrying every error | retries NotFound and validation failures forever | is_retryable() on the error type |
.unwrap_or_default() on errors that matter | turns failures into silent wrong data | handle or propagate; default only where it is the specified behaviour |
rust-borrow-checker-error-explainer
Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.
rust-cargo-workspace-designer
Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.
rust-lifetime-annotation-advisor
Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.
rust-tokio-async-service-builder
Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.
rust-trait-design-reviewer
Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.
rust-unsafe-block-auditor
Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.