How to pattern match on error types in Rust

Use match or if let to destructure Result or custom error enums and handle specific failure cases in Rust.

Use the match control flow operator to destructure Result or custom enum error types and handle each variant explicitly.

match result {
    Ok(value) => println!("Success: {}", value),
    Err(e) => println!("Error: {}", e),
}

For custom errors defined as an enum, match on the specific variant names to access their data.

match error {
    MyError::NotFound(id) => println!("ID {} missing", id),
    MyError::InvalidInput(msg) => println!("Bad input: {}", msg),
}

Use if let for concise handling when you only care about one specific error variant.

if let Err(MyError::NotFound(id)) = result {
    println!("Could not find ID: {}", id);
}

The ? operator automatically propagates errors up the call stack if you do not handle them locally.

let value = risky_operation()?;

Refer to ch06-02-match.md for match syntax and ch09-02-recoverable-errors-with-result.md for Result details.