【发布时间】:2021-07-24 22:02:47
【问题描述】:
我正在使用thiserror crate 创建自定义错误类型
use thiserror::Error;
/// ParseTreeError enumerates all possible errors returned by this library.
#[derive(Error, Debug)]
pub enum ParseTreeError {
/// Represents an empty source. For example, an empty text file being given
/// as input to `count_words()`.
#[error("Source contains no data")]
EmptySource,
/// Represents a failure to read from input.
#[error("Read error")]
ReadError,
}
pub struct Parser <'a, T>
where
T: FromStr + PartialEq
{
token_stream: &'a str,
marker: (usize, usize),
}
impl<'a, T> Parser<'a, T>
where
T: FromStr + PartialEq
{
fn test_parse() -> Result<(), ParseTreeError> {
let mut val = T::from_str("5").unwrap();
Ok(())
}
}
这会引发以下错误:
error[E0599]: the method `unwrap` exists for enum `std::result::Result<T, <T as FromStr>::Err>`, but its trait bounds were not satisfied
--> src/tree/parser.rs:65:40
|
65 | let mut val = T::from_str("5").unwrap();
| ^^^^^^ method cannot be called on `std::result::Result<T, <T as FromStr>::Err>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`<T as FromStr>::Err: Debug`
如果我像这样映射错误
let mut val2 = T::from_str("5").map_err(|_| ParseTreeError::ReadError).unwrap();
然后不会抛出错误。
如果我尝试使用 ?操作员我得到错误
error[E0277]: `?` couldn't convert the error to `ParseTreeError`
--> src/tree/parser.rs:65:40
|
65 | let mut val1 = T::from_str("5")?;
| ^ the trait `From<<T as FromStr>::Err>` is not implemented for `ParseTreeError`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= note: required by `from`
我需要做什么才能使 ? operator 可以自动将错误转换为正确的错误类型,而无需使用 map_err ?
【问题讨论】:
-
要解包,您可以添加
T::Err: Debug绑定。要使用?进行转换,您可以使用#[from]注释,如thiserror 文档中所述。 -
@IbraheemAhmed 感谢您的建议,T::Err 是什么意思?所有类型都有吗?
-
另外,我应该在哪个错误上使用#[from],是否存在所有 FromStr 实现都返回的常见错误?
标签: rust