#anyhow #attr #error-context #macro-attributes #produce

macro context_attr

Attribute macro to add context to all errors a function produces

6 releases

0.1.5 Jun 9, 2025
0.1.4 Jan 10, 2025
0.1.1 Oct 3, 2024
0.1.0 Aug 13, 2024

#1120 in Procedural macros

Download history 72/week @ 2025-10-09 79/week @ 2025-10-16 115/week @ 2025-10-23 14/week @ 2025-10-30 23/week @ 2025-11-06 63/week @ 2025-11-13 52/week @ 2025-11-20 50/week @ 2025-11-27 52/week @ 2025-12-04 54/week @ 2025-12-11 34/week @ 2025-12-18 21/week @ 2025-12-25 4/week @ 2026-01-01 32/week @ 2026-01-08 11/week @ 2026-01-15 15/week @ 2026-01-22

62 downloads per month

MIT license

6KB
68 lines

Add a context to the result returned from the annotated function, regardless of return path.

#[context_attr::anyhow("Doing thing")]
fn do_thing() -> anyhow::Result<()> {
  if true {
    anyhow::bail!("Can't do thing");
  }
  anyhow::bail!("Another error path");
}

This is most useful when there are multiple error points in a function, and annotating the context of the function at each point adds too much noise.

Format

You can call std::format to include function arguments in the message.

#[context_attr::anyhow(format!("The number: {x}"))]
fn add_one(x: u32) -> anyhow::Result<()> { todo!() }

Note: that the format string is eagerly created at the beginning of the function. There currently isn't a way around this, as arguments to the function may be moved.

Works with

The annotation works with:

  • Async functions
  • Functions in impl blocks

Dependencies

~235–700KB
~15K SLoC