2

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?

Ítalo Cunha
  • 21
  • 1
  • 2
  • Look at the [failure](https://rust-lang-nursery.github.io/failure/) crate, which intends to eventually supersede the std error management mechanism. – Jmb Jul 17 '19 at 06:14
  • @Jmb failure is deprecated and should not be recommended for new projects. – Shepmaster May 13 '20 at 14:33
  • *a way to implement `std::convert::From`* — this isn't a well-formed type (at least not the way you mean it). See [What does “dyn” mean in a type?](https://stackoverflow.com/q/50650070/155423) – Shepmaster May 13 '20 at 14:35
  • TL;DR the duplicates — no, there's not. You'd have to do `impl std::convert::From for ParseError` but that will conflict as soon as you have a second `From` impl – Shepmaster May 13 '20 at 14:40
  • @Shepmaster just curious if a new better approach exists for supporting this use-case now that it's been a few years? – ecoe Aug 19 '23 at 20:24

0 Answers0