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

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

#193 in Procedural macros

Download history 3618/week @ 2024-01-05 3707/week @ 2024-01-12 3814/week @ 2024-01-19 4172/week @ 2024-01-26 4513/week @ 2024-02-02 4857/week @ 2024-02-09 4307/week @ 2024-02-16 3685/week @ 2024-02-23 5054/week @ 2024-03-01 5349/week @ 2024-03-08 5228/week @ 2024-03-15 4492/week @ 2024-03-22 3644/week @ 2024-03-29 3440/week @ 2024-04-05 3970/week @ 2024-04-12 3662/week @ 2024-04-19

15,225 downloads per month
Used in 7 crates

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

~0.4–0.8MB
~20K SLoC