Skip to content
Rust

Error Handling

Result and the ? operator.

By EZ4Code Team
errorerror-handling

Code

use std::fs;
use std::io;
use std::num::ParseIntError;

// Custom error
#[derive(Debug)]
enum AppError {
    Io(io::Error),
    Parse(ParseIntError),
    NotFound(String),
}

impl From<io::Error> for AppError {
    fn from(e: io::Error) -> Self { AppError::Io(e) }
}
impl From<ParseIntError> for AppError {
    fn from(e: ParseIntError) -> Self { AppError::Parse(e) }
}

// ? operator propagates errors
fn read_config() -> Result<i32, AppError> {
    let content = fs::read_to_string("config.txt")?; // io::Error -> AppError
    let num: i32 = content.trim().parse()?; // ParseIntError -> AppError
    Ok(num)
}

fn main() {
    match read_config() {
        Ok(n) => println!("Config value: {}", n),
        Err(e) => eprintln!("Error: {:?}", e),
    }

    // unwrap and expect
    let result: Result<i32, &str> = Ok(42);
    println!("{}", result.unwrap());
    println!("{}", result.expect("should be ok"));
}

Explanation

Result<T, E> is for recoverable errors; the ? operator propagates errors; the From trait implements error conversion.

More Rust Snippets