6 个版本 (破坏性更新)
0.5.0 | 2019年11月28日 |
---|---|
0.4.0 | 2019年11月5日 |
0.3.0 | 2019年9月8日 |
0.2.0 | 2019年7月19日 |
0.1.1 | 2019年7月18日 |
#84 in #read-file
用于 evitable
46KB
1.5K SLoC
Evitable
Evitable 是一个用于轻松创建和使用自定义错误类型的库。它旨在使创建自定义领域特定错误类型更容易,同时减少将底层错误转换为领域特定错误的噪音,同时保持底层错误作为 source()
。此软件包默认启用一个名为 derive
的功能,该功能启用派生 ErrorContexts。
快速示例
此示例展示了调用某个 API 的典型用例,该 API(假装)读取文件,然后失败,并将错误转换为领域特定错误。
use evitable::*;
// Typically, this is in another file
mod error {
use super::*;
#[evitable]
pub enum ParseContext {
#[evitable(description = "Io error", from = std::io::Error)]
Io,
#[evitable(description("Invalid token. Expected {}, was {}.", expected, actual))]
InvalidToken {
expected: String,
actual: String,
},
}
}
use error::*;
// pretend token type
#[derive(Debug)]
pub enum Token {
EndOfFile,
}
fn read_file() -> Result<String, std::io::Error> {
// we're pretending to read a file here
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
}
// main function
fn parse_file() -> ParseResult<Token> {
let content = read_file()?;
ensure!(content == "EOF", ParseContext::InvalidToken {
expected: "EOF".to_owned(),
actual: content,
});
Ok(Token::EndOfFile)
}
let result = parse_file();
let err = result.unwrap_err();
assert_eq!(err.kind(), ParseErrorKind::Io);
依赖项
~1.5MB
~36K SLoC