Attribute Macro fn_error_context::context[][src]

#[context]
Expand description

Add context to errors from a function.

The arguments to this macro are a format string with arguments using the standard std::fmt syntax. Arguments to the function can be used as long as they are not consumed in the function body.

This macro desugars to something like

pub fn function() -> anyhow::Result<()> {
    (|| -> anyhow::Result<()> {
        function_body()
    })().map_err(|err| err.context("context"))
}

Sometimes you will receive borrowck errors, especially when returning references. These can often be fixed by setting the move option of the attribute macro. For example:

use fn_error_context::context;

#[context(move, "context")]
fn returns_reference(val: &mut u32) -> anyhow::Result<&mut u32> {
    Ok(&mut *val)
}