Search code examples
error-handlingrustcode-reuse

How to construct a ParseIntError in my own code?


I want to reuse the standard library's ParseIntError in my function. However, I'm implementing parsing of the input string myself, so I don't need to return an error value returned by the standard library.

I didn't find a way to construct ParseIntError value. The only solution I found looks like this:

use std::num::ParseIntError;

fn from_str_radix(s: &str, radix: u32) -> Result<(), ParseIntError> {
    let error_empty = "".parse::<i32>().expect_err("get empty input error");
    let error_invalid_digit = "Z".parse::<i32>().expect_err("get invalid digit error");

    if s.is_empty() {
        return Err(error_empty);
    }

    for c in s.chars().rev() {
        match c.to_digit(radix) {
            None => return Err(error_invalid_digit),
            _ => unimplemented!(),
        }
    }

    Ok(())
}

Is there more elegant way to return ParseIntError from my own code?


Solution

  • There is currently no way to construct a ParseIntError yourself. As you find it, there is an open issue that asks to make it public. However, I don't think it's a good idea.

    ParseIntError is the error of num module. It isn't made to be used by everyone that would implement a parsing crate because you should have your own potential error. You could use IntErrorKind but I still don't think is a good thing because you could end by not having the same error.

    So, I think you should have your own error type, and maybe use the same design, have an enum with #[non_exhaustive] attribute. You should not hesitate to use your own error in your own code. See very good article Error Handling In Rust - A Deep Dive. (I personally doesn't agree with everything in the article but that still high quality, I recommend using snafu or thiserror)