autocontext
A tiny procedural macro that automatically attaches
anyhow::Context
to function results. No more sprinkling .context() over every fallible function.
Why?
Without autocontext:
With autocontext:
The error chain still reads:
Error: deploy
Caused by:
connection refused: 127.0.0.1:5432
Installation
[]
= "0.1"
= "1"
Usage
Default mode -- context on the whole function
use autocontext;
use Result;
The context message defaults to the function name.
Custom message
Argument logging
Include function argument values in the context message (via Debug):
#[autocontext(args(path, retries))]
fn connect(path: &str, retries: u32) -> Result<Connection> {
// ...
}
On error:
Error: connect: path="/tmp/sock" retries=3
Caused by:
connection refused
You can combine with a custom message:
// Error: establishing connection: path="/tmp/sock"
Per-try mode -- context on every ?
Useful when a function has many fallible steps and you need to know which one failed without reading a backtrace.
Per-try + arguments
#[autocontext(per_try, args(user_id, attempt))]
fn authenticate(user_id: u64, attempt: u8) -> Result<()> {
let _token = issue_token(user_id)?;
verify(attempt)?;
Ok(())
}
On error:
Error: authenticate [try #0]: user_id=0 attempt=1
Caused by:
invalid user
Async functions
Works out of the box:
#[autocontext]
async fn fetch_user(client: &reqwest::Client, id: u64) -> Result<User> {
let resp = client.get(format!("/users/{id}")).send().await?;
let user = resp.json::<User>().await?;
Ok(user)
}
Attribute syntax reference
| Syntax | Effect |
|---|---|
| #[autocontext]` | Context = function name (static, no allocation on success) |
| #[autocontext("msg")] | Context = custom string |
| #[autocontext(per_try)] | Context on every ? operator |
| #[autocontext(args(a, b))] | Include a, b (via Debug) in message |
| #[autocontext(per_try, args(a, b))] | Combined |
| #[autocontext("msg", args(a, b))] | Combined |
Options are comma-separated and fully combinable.
How it works
| Mode | Expansion |
|---|---|
| default (sync) | Body wrapped in immediately-invoked closure; .context(msg) or .with_context( |
| default (async) | Body wrapped in async block + .await; same context logic. |
| per_try | Every expr? rewritten to expr.with_context( |
Functions that do not return Result are emitted unchanged.
Per-try semantics
- Only the ? operator is instrumented. A bare return Err(...) or return some_fallible_fn() does not receive context.
- When an error propagates through multiple ? sites (e.g. nested closures), each site appends its own context layer. Use err.chain() to inspect the full chain, or err.root_cause() for the original error.
- Numbering is sequential across the entire function body (including nested closures), following source reading order.
Notes & Limitations
- Requires return type Result or Result<T, E> where E: Intoanyhow::Error.
- Arguments passed to args(...) must implement Debug.
- Formatting occurs only on error -- with_context closure is not called on the success path.
MSRV
Rust 1.70 (edition 2021). No nightly features required.
License
MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)