2 个版本
0.1.1 | 2019 年 9 月 16 日 |
---|---|
0.1.0 | 2019 年 9 月 16 日 |
#2130 in Rust 模式
5KB
该软件包提供了一个 trait,名为 ErrWith
,并有一个方法,名为 err_with
。 ErrWith
为 Result<T, E>
实现,其中 result.err_with(w)
将 Err(e)
转换为 Err((e,w))
,并保持 Ok(...)
不变。
这本身并不特别有用,但可以用来定义从 (E, W)
到自定义错误类型的转换,因此可以记录和稍后报告错误上下文。
例如
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(())
}