[][src]Crate context_attribute

Set the error context using doc comments.

This is useful because instead of writing manual error messages to provide context to an error, it automatically derives it from doc comments. This works especially well for async contexts, where stack traces may not be persisted past yield points and thread boundaries. But contexts do.


use context_attribute::context;
use failure::{ensure, ResultExt};

/// Square a number if it's less than 10.
fn square(num: usize) -> Result<usize, failure::Error> {
    ensure!(num < 10, "Number was too large");
    Ok(num * num)

fn main() -> Result<(), failure::Error> {
    let args = std::env::args();
    ensure!(args.len() == 2, "usage: square <num>");
    let input = args.skip(1).next().unwrap().parse()?;

    println!("result is {}", square(input)?);

$ cargo run --example square 12
Error: ErrorMessage { msg: "Number was too large" }
Square a number if it's less than 10.

Attribute Macros


Use a doc comment to annotate the failure context of a function or try block.