If someone is looking for another alternative, please check out my SNAFU crate:
A quick list of features:
- Wraps underlying errors with additional domain-specific information
- Provides backtraces when desired
- Easily specify
Display
- Uses the Rust
std::error::Error
trait - Supports Rust 1.18+
- Designed for use in libraries or applications
Using an example from above, the same functionality would look like:
#[derive(Debug, Snafu)]
pub enum MyError {
#[snafu(display("error while opening file: {}", source))],
CannotOpenFile { source: io::Error },
CannotReadData { source: io::Error },
}
You'd use this as
fs::open(filename).context(CannotOpenFile)?;
However, I'd encourage adding more detail to the error message:
#[derive(Debug, Snafu)]
pub enum MyError {
#[snafu(display("error while opening file {}: {}", filename.display(), source))],
CannotOpenFile { source: io::Error, filename: path::PathBuf },
CannotReadData { source: io::Error, filename: path::PathBuf },
}
And using it like:
fs::open(filename).context(CannotOpenFile { filename })?;