Propagate errors in Rust by returning Result types and using the ? operator to automatically pass failures up the call stack.
Propagate errors in Rust by returning a Result type and using the ? operator to short-circuit on failure. This automatically unwraps Ok values and returns Err values up the call stack.
use std::fs::File;
use std::io::{self, Read};
fn read_file(path: &str) -> io::Result<String> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
Error propagation is how you pass a problem from one part of your code to another without stopping the whole program. Instead of crashing immediately, your function says, "I couldn't do this, here is the error," and lets the caller decide what to do next. It is like a worker handing a defective part to their supervisor instead of throwing it on the floor.