Expand description
This library provides an error wrapper which adds a description to its specific instance.
§Examples
For example, you want to create file on the given path and write here a given string.
Let’s forget for a moment that std::fs::write
exists and do it ourselves:
use std::io::Write;
fn create_and_write(path: &Path, content: &str) -> Result<(), io::Error> {
let mut file = File::create(path)?;
write!(file, "{}", content)?;
file.sync_all()
}
Here are three distinct sources of error, and it might not always be obvious
which of them is the real one in particular case. That’s how it is handled with describe_err
:
use std::io::Write;
use describe_err::{describing, describe, Described};
fn create_and_write(path: &Path, content: &str) -> Result<(), Described<io::Error>> {
let mut file = describing!(File::create(path))?;
write!(file, "{}", content).map_err(describe("Cannot write to file"))?;
describing!(file.sync_all())
}
Here you can see two ways to use the library:
- By explicitly providing the description with
describe
. This function returns the closure, which maps an incoming error toDescribed
instance. - By wrapping the
Result
-producing operation indescribing!
macro, which will describe the error with the stringified content.
And here’s how will be used the generated output:
fn main() {
let path = PathBuf::from("/tmp/nonexistent/path");
let res = create_and_write(&path, "arbitrary content");
let err = res.unwrap_err();
assert_eq!(err.to_string(), "File::create(path): No such file or directory (os error 2)");
}
As you can see, the command which produced an error is right here, in the error itself.
Macros§
- Wrap an error with an auto-generated description.
Structs§
- An error wrapper with description.
Functions§
- Wrap an error with description.