2 个不稳定版本
| 0.2.0 | 2023 年 8 月 12 日 |
|---|---|
| 0.1.0 | 2022 年 10 月 23 日 |
在 Rust 模式 中排名 #2453
37KB
383 行
Exun
有许多我们预料不到的错误。但如果我们错了怎么办?我们不希望我们的程序因为这一点而崩溃。我们也不想花费太多时间处理意外错误。这就是这个库的作用。你保留你的意外错误,稍后再处理。
-
这个库在
no-std中工作。如果使用alloc或std,则会有一些额外的功能。 -
Exun是一个错误类型。如果你有一个Unexpected错误,它将保留它,这样你就可以稍后确定如何处理它。如果错误是Expected,它也会保留。 -
RawUnexpected将所有意外错误封装起来。还有一个UnexpectedError,它实现了Error。 -
Expect是Exun<E, RawUnexpected>的类型别名。 -
通过调用
Result::unexpect明确标记你不期望发生的错误。如果错误类型没有实现Error,只要它实现了Debug + Display + Send + Sync + 'static,你仍然可以使用Result::unexpect_msg。
用法
唯一先决条件是 Rust 1.41.1。
对于标准功能
[dependencies]
# ...
exun = "0.2"
以下功能默认启用
-
std:这会自动启用alloc。它用于标准库的Error类型。使用此类型可以使更多错误自动转换为Exun和RawUnexpected错误,并且对于Result::unexpect是必需的。 -
alloc:这是为了让RawUnexpected和UnexpectedError能够存储字符串消息所必需的。这可以通过使用Result::unexpect_mshg来实现。没有这个功能,只能构建相当于Result::unexpect_none的结果。
要禁用这些功能
[dependencies]
# ...
exun = { version = "0.2", default-features = false }
如果您想使用 alloc 但不使用 std
[dependencies]
# ...
exun = { version = "0.2", default-features = false, features = ["alloc"] }
示例
use exun::*;
fn foo(num: &str) -> Result<i32, RawUnexpected> {
// we use `unexpect` to indicate that we don't expect this error to occur
let num = num.parse::<i32>().unexpect()?;
Ok(num)
}
use exun::*;
fn first(list: &[i32]) -> Result<i32, RawUnexpected> {
// for options, the `unexpect_none` method can be used
let num = list.get(0).unexpect_none()?;
Ok(num)
}
use std::error::Error;
use std::fmt::{self, Display};
use exun::*;
#[derive(Debug)]
struct NoNumberError;
impl Display for NoNumberError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "no number provided")
}
}
impl Error for NoNumberError {}
fn foo(num: Option<&str>) -> Result<i32, Expect<NoNumberError>> {
let num = num.ok_or(NoNumberError)?; // we expect that this may return an error
let num = num.parse::<i32>().unexpect()?; // but we think the number is otherwise parsable
Ok(num)
}
use std::error::Error;
use std::fmt::{self, Display};
use std::num::ParseIntError;
use exun::*;
#[derive(Debug)]
struct NoNumberError;
impl Display for NoNumberError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "no number provided")
}
}
impl Error for NoNumberError {}
fn foo(num: Option<&str>) -> Result<i32, Exun<&str, ParseIntError>> {
// we expect it possible to not get a number, so we handle it as such
let num = match num {
Some(num) => num,
None => return Err(Expected("no number provided")),
};
// however, we expect that the number is otherwise parsable
match num.parse() {
Ok(int) => Ok(int),
Err(e) => Err(Unexpected(e))
}
}