I have implemented a custom error class in a module that reads from a CSV file. As different errors can occur while reading the file, I have implemented the std::convert::From
for all types of errors that can occur in the code. However, given I do not need any information about the errors themselves, I wish I could just implement From<Error>
(or use a more streamlined approach).
This is the code implementing the custom error:
#[derive(Debug)]
pub struct ParseError {
kind: ParseErrorKind,
message: String,
}
#[derive(Eq, PartialEq, Hash, Debug)]
pub enum ParseErrorKind {
Untracked,
TrackedError1,
TrackedError2,
TrackedErrorN,
}
impl std::convert::From<std::num::ParseIntError> for ParseError {
fn from(error: std::num::ParseIntError) -> Self {
ParseError {
kind: ParseErrorKind::Untracked,
message: error.to_string(),
}
}
}
impl std::convert::From<std::num::ParseFloatError> for ParseError {
fn from(error: std::num::ParseFloatError) -> Self {
ParseError {
kind: ParseErrorKind::Untracked,
message: error.to_string(),
}
}
}
It is generated in functions that parse CSV records:
fn from_record(rec: &HashMap<String, String>) -> Result<Info, ParseError> {
Ok(Info {
field: rec["column"].parse::<u32>()?,
})
}
And I use the error in the the loader function to count tracked errors:
// let error_counts: HashMap<ParseErrorKind, u64>;
let info = match Info::from_record(&record) {
Ok(i) => i,
Err(e) => {
*error_counts.entry(e.kind).or_insert(0) += 1;
continue;
}
};
Is there a way to implement std::convert::From<std::error::Error>
, or are there other streamlined approaches?