Back to listRust
Rust Error Handling Pattern
Lv.5812@mukitaro13 playsDec 28, 2025
Rust error handling with custom error types. Idiomatic Rust pattern.
preview.rust
1use std::fs::File;2use std::io::{self, Read};3 4#[derive(Debug)]5enum AppError {6 Io(io::Error),7 Parse(std::num::ParseIntError),8 Custom(String),9}10 11impl From<io::Error> for AppError {12 fn from(err: io::Error) -> Self {13 AppError::Io(err)14 }15}16 17impl From<std::num::ParseIntError> for AppError {18 fn from(err: std::num::ParseIntError) -> Self {19 AppError::Parse(err)20 }21}22 23fn read_number_from_file(path: &str) -> Result<i32, AppError> {24 let mut file = File::open(path)?;25 let mut contents = String::new();26 file.read_to_string(&mut contents)?;27 let number: i32 = contents.trim().parse()?;28 Ok(number)29}30 31fn main() {32 match read_number_from_file("number.txt") {33 Ok(n) => println!("Number: {}", n),34 Err(e) => eprintln!("Error: {:?}", e),35 }36}Custom problems are not included in rankings