How to Implement From for Custom Error Conversion

Implement the From trait for your custom error enum to enable automatic conversion from standard library errors using the ? operator.

Implement the From trait for your custom error type to enable automatic conversion from other error types using the ? operator.

use std::fmt;

#[derive(Debug)]
enum MyError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
}

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MyError::Io(e) => write!(f, "IO error: {e}"),
            MyError::Parse(e) => write!(f, "Parse error: {e}"),
        }
    }
}

impl std::error::Error for MyError {}

impl From<std::io::Error> for MyError {
    fn from(err: std::io::Error) -> Self {
        MyError::Io(err)
    }
}

impl From<std::num::ParseIntError> for MyError {
    fn from(err: std::num::ParseIntError) -> Self {
        MyError::Parse(err)
    }
}

fn run() -> Result<(), MyError> {
    let _data = std::fs::read_to_string("file.txt")?;
    let _num: i32 = "123".parse()?;
    Ok(())
}