#error-context #macro #attributes #add #anyhow

macro fn-error-context

An attribute macro to add context to errors from a function

5 releases

0.2.1 Mar 21, 2023
0.2.0 Jul 7, 2021
0.1.2 Apr 21, 2021
0.1.1 Jul 11, 2020
0.1.0 Mar 29, 2020

#316 in Procedural macros

Download history 4104/week @ 2024-07-23 3908/week @ 2024-07-30 3778/week @ 2024-08-06 3546/week @ 2024-08-13 3202/week @ 2024-08-20 3833/week @ 2024-08-27 4365/week @ 2024-09-03 3079/week @ 2024-09-10 3369/week @ 2024-09-17 3981/week @ 2024-09-24 4393/week @ 2024-10-01 3740/week @ 2024-10-08 3822/week @ 2024-10-15 4963/week @ 2024-10-22 4398/week @ 2024-10-29 3960/week @ 2024-11-05

17,947 downloads per month
Used in 14 crates (11 directly)

MIT/Apache

14KB
55 lines

Crates.io Docs.rs

fn-error-context

An attribute macro to add context to errors from a function.

#[context("failed to parse config at `{}`", path.display())]
pub fn parse_config(path: &Path) -> anyhow::Result<u32> {
    let text = read_to_string(path)?;
    Ok(text.parse()?)
}

lib.rs:

This crate provides the context macro for adding extra error information to a function.

Works with anyhow, failure and any other error type which provides a context method taking a string.

#
use fn_error_context::context;

#[context("failed to parse config at `{}`", path.as_ref().display())]
pub fn parse_config(path: impl AsRef<Path>) -> anyhow::Result<u32> {
    let text = read_to_string(path.as_ref())?;
    Ok(text.parse()?)
}

let error = parse_config("not-found").unwrap_err();
assert_eq!(
    error.to_string(),
    "failed to parse config at `not-found`",
);
assert_eq!(
    error.source().unwrap().downcast_ref::<io::Error>().unwrap().kind(),
    io::ErrorKind::NotFound,
);

Dependencies

~250–700KB
~17K SLoC