#anyhow #context #error #trace #source #location #macro

macro anyhow_trace

Macro which adds source location as context to anyhow errors

4 releases

0.1.3 Mar 24, 2024
0.1.2 Mar 21, 2024
0.1.1 Mar 21, 2024
0.1.0 Mar 21, 2024

#1954 in Procedural macros

Download history 56/week @ 2024-06-07 54/week @ 2024-06-14 61/week @ 2024-06-21 45/week @ 2024-06-28 120/week @ 2024-07-05 72/week @ 2024-07-12 65/week @ 2024-07-19 132/week @ 2024-07-26 86/week @ 2024-08-02 52/week @ 2024-08-09 62/week @ 2024-08-16 101/week @ 2024-08-23 78/week @ 2024-08-30 96/week @ 2024-09-06 64/week @ 2024-09-13 44/week @ 2024-09-20

298 downloads per month
Used in 11 crates (2 directly)

MIT license

6KB
75 lines

This macro re-writes try expressions to add a call to anyhow::Context::with_context which adds the source location of the try expression as context to the error.

This creates something that is similar to a backtrace, but is actually the path the error propagates through instead. This can be preferable to using anyhow's backtrace feature because it doesn't rely on unwinding the stack or debugging symbols being compiled in.

Here is an example

use anyhow_trace::anyhow_trace;
use anyhow::{bail, Result};

fn foo_err() -> Result<()> {
    bail!("this is foo error")
}

struct FooBar;

#[anyhow_trace]
impl FooBar {
    fn thing() -> Result<()> {
        fn im_inside() -> Result<()> {
            foo_err()?;
            Ok(())
        }
        im_inside()?;
        Ok(())
    }
}

#[anyhow_trace]
fn inner() -> Result<()> {
    FooBar::thing()?;
    Ok(())
}

#[anyhow_trace]
fn main() -> Result<()> {
    inner()?;
    Ok(())
}

This prints out the following:

Error: main at examples/example.rs:30:5

Caused by:
    0: inner at examples/example.rs:24:5
    1: FooBar::thing at examples/example.rs:17:9
    2: FooBar::thing::im_inside at examples/example.rs:14:13
    3: this is foo error

Dependencies

~275–730KB
~17K SLoC