fn-error-context
A Rust attribute macro that automatically adds contextual messages to errors returned from a function.
Repository Health
Technical Analysis
fn-error-context is a small Rust procedural-macro crate that provides a context attribute for annotating functions with an error-context message. When the function returns an error, the macro wraps it with the formatted context, giving you anyhow-style contextual error messages without manually calling .context() at every fallible expression inside the function.
What You Get
- A context attribute macro for functions returning Result
- Automatic, format-string-based context on all error return paths
- Interoperability with anyhow-style error context
- A tiny dependency with a focused, single-purpose API
Common Use Cases
- Adding uniform error context to fallible functions without boilerplate
- Producing readable error chains that name the operation that failed
- Reducing repetitive .context() calls scattered through a function body
Under The Hood
Architecture
The crate is a procedural macro that parses the annotated function and its context attribute arguments, then rewrites the function body so its Result return value is wrapped with the formatted context on error paths. The expansion routes through a trait compatible with anyhow’s context mechanism, so the added message becomes part of the error chain.
Tech Stack
A Rust proc-macro crate built with syn and quote for parsing and code generation. Dual-licensed Apache-2.0 OR MIT and published on crates.io as fn-error-context.
Code Quality
Despite its small size, the crate ships an integration test suite under tests/ and worked examples under examples/, exercising the macro across function shapes. It is stable and unchanged for long stretches, reflecting a finished, single-purpose design rather than neglect.
API Design
The API is a single attribute with format-string ergonomics identical to println!, making it immediately intuitive for Rust developers. There is virtually no learning curve beyond knowing anyhow-style error context.