Error Handling Patterns
Rust's error handling is explicit and composes well. This lesson is the patterns you'll actually meet in production Rust.
Custom Error Types
#[derive(Debug)]enum AppError { IoError(std::io::Error), ParseError(String), NotFound(String),}
impl std::fmt::Display for AppError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { AppError::IoError(e) => write!(f, "IO error: {}", e), AppError::ParseError(msg) => write!(f, "Parse error: {}", msg), AppError::NotFound(name) => write!(f, "Not found: {}", name), } }}
impl From<std::io::Error> for AppError { fn from(e: std::io::Error) -> Self { AppError::IoError(e) }}Once From is wired up, ? quietly converts io::Error into AppError for you.
Using the ? Operator with Custom Errors
fn load_config(path: &str) -> Result<Config, AppError> { let contents = std::fs::read_to_string(path)?; // io::Error -> AppError let port: u16 = contents.trim().parse() .map_err(|_| AppError::ParseError("invalid port".into()))?; Ok(Config { port })}? and From team up to give you clean error propagation. Each function declares what errors it can return, and the conversions slot in automatically. That's the slot try/catch fills in other languages.
The anyhow Pattern
In application code (not libraries), the anyhow crate cuts the boilerplate down hard:
// With anyhow, any error type works. fetch_data and process stand in// for your own functions; each can return a different error type.fn main() -> anyhow::Result<()> { let config = load_config("config.txt")?; let data = fetch_data(&config)?; process(data)?; Ok(())}Panic vs Result
panic!- unrecoverable error, program crashesResult- recoverable error, caller decides what to do
// Use panic for programmer errors (bugs)fn get_element(v: &[i32], i: usize) -> i32 { v[i] // panics on out-of-bounds - this is a bug in the caller}
// Use Result for expected failuresfn read_file(path: &str) -> Result<String, std::io::Error> { std::fs::read_to_string(path) // file might not exist - that is expected}Error Handling in main()
fn main() { if let Err(e) = run() { eprintln!("Error: {}", e); std::process::exit(1); }}
fn run() -> Result<(), AppError> { let config = load_config("config.txt")?; println!("Running on port {}", config.port); Ok(())}main stays clean, and you get to use ? everywhere underneath it.
Here's a version you can run, with Config defined and all three variants in use. There's no config.txt in the runner, so the last line shows From turning an io::Error into AppError::IoError.
Challenges
Create a TrafficLight enum and use match to print the duration of each color.