book icon indicating copy to clipboard operation
book copied to clipboard

error handling: add enum idiom

Open 89z opened this issue 3 years ago • 0 comments

Coming from another language, I have struggled with Rust error system for a while. The main issue I have, is when a function can return different error types. I know about Box<dyn Error>, but that solution has never felt quite right to me. I have wanted a way to say "return this error or that error". The other day, I found this [1]:

enum CliError {
    IoError(io::Error),
    ParseError(num::ParseIntError),
}

impl From<io::Error> for CliError {
    fn from(error: io::Error) -> Self {
        CliError::IoError(error)
    }
}

impl From<num::ParseIntError> for CliError {
    fn from(error: num::ParseIntError) -> Self {
        CliError::ParseError(error)
    }
}

which is exactly what I have been looking for. Its boilerplate, but after that you can just use CliError which is really nice. Also I have seen other crates using this method. I checked the entire error chapter [2][3][4][5], and I didn't really see this method discussed, other than this small comment:

For example, we could change the read_username_from_file function in Listing 9-7 to return a custom error type named OurError that we define. If we also define impl From<io::Error> for OurError to construct an instance of OurError from an io::Error, then the ? operator calls in the body of read_username_from_file will call from and convert the error types without needing to add any more code to the function.

this is helpful, but the text and example in std::convert::From really crystallized the idea for me. I think it would be useful to copy or adapt the example from std::convert::From into the Book.

  1. https://doc.rust-lang.org/std/convert/trait.From.html
  2. https://doc.rust-lang.org/book/ch09-00-error-handling.html
  3. https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
  4. https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
  5. https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html

89z avatar Sep 12 '22 21:09 89z