book
                                
                                 book copied to clipboard
                                
                                    book copied to clipboard
                            
                            
                            
                        error handling: add enum idiom
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_filefunction in Listing 9-7 to return a custom error type namedOurErrorthat we define. If we also defineimpl From<io::Error> for OurErrorto construct an instance ofOurErrorfrom anio::Error, then the?operator calls in the body ofread_username_from_filewill 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.
- https://doc.rust-lang.org/std/convert/trait.From.html
- https://doc.rust-lang.org/book/ch09-00-error-handling.html
- https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
- https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
- https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html