Mapping Errors

Now let's get more rust idiomatic by using .map_err().

use chainerror::*;

use std::error::Error;
use std::io;
use std::result::Result;

fn do_some_io() -> Result<(), Box<Error + Send + Sync>> {
    Err(io::Error::from(io::ErrorKind::NotFound))?;
    Ok(())
}

fn func2() -> Result<(), Box<Error + Send + Sync>> {
    do_some_io().map_err(|e| cherr!(e, "func2 error"))?;
    Ok(())
}

fn func1() -> Result<(), Box<Error + Send + Sync>> {
    func2().map_err(|e| cherr!(e, "func1 error"))?;
    Ok(())
}

fn main() -> Result<(), Box<Error + Send + Sync>> {
    if let Err(e) = func1() {
        eprintln!("{:?}", e);
    }
    Ok(())
}
#[allow(dead_code)]
mod chainerror {
{{#includecomment ../src/lib.rs}}
}

If you compare the output to the previous example, you will see, that:

Error: src/main.rs:19: "func1 error"

changed to just:

src/main.rs:16: "func1 error"

This is, because we caught the error of func1() in main() and print it out ourselves.

We can now control, whether to output in Debug or Display mode. Maybe depending on --debug as a CLI argument.