err-with 0.1.1

🤔 Trait for adding context to errors
Documentation
  • Coverage
  • 33.33%
    1 out of 3 items documented1 out of 3 items with examples
  • Size
  • Source code size: 9.71 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.03 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • Homepage
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • casey

This crate provides a single trait, ErrWith, with one method, err_with. ErrWith is implemented for Result<T, E>, with result.err_with(w) transforming an Err(e) to an Err((e,w)), and leaving an Ok(...) unchanged.

This is not particularly useful on its own, but can be used to define conversions from (E, W) into your custom error types, so error contexts can be recorded and reported later.

For example:

use std::{fs, io, path::{Path, PathBuf}};

use err_with::ErrWith;

// Given this custom error type:
#[derive(Debug)]
enum Error {
  Io { io_error: io::Error, path: PathBuf },
}

// We can define a conversion from `(io::Error, AsRef<Path>)` to our
// custom error type:
impl<P: AsRef<Path>> From<(io::Error, P)> for Error {
    fn from((io_error, path): (io::Error, P)) -> Error {
        Error::Io {
            path: path.as_ref().to_owned(),
            io_error,
        }
    }
}

// Which allows us to attach the path of an I/O error and convert
// the error into our custom error type in an ergonomic fashion:
fn main() -> Result<(), Error> {
    fs::read_to_string("foo/bar").err_with("foo/bar")?;
    Ok(())
}