Search⌘ K
AI Features

Errors

Explore how Rust manages errors with the Result type, using pattern matching and the ? operator for clean handling. Understand when to use unwrap and expect, and learn how the anyhow crate helps handle multiple error types for safer, scalable web development.

Most languages handle errors through exceptions, but Rust does it with a type called Result<T, E>. It’s a data type with two generics: T and E. The T type on the left side is used for the return value, and the E is for the error. We need to return it with the Ok and Error function, respectively.

Rust 1.40.0
// This is an example function that simply takes a parameter as string and return
// the expected type for "This works" or an error for everything else.
fn this_an_example(some_parameter: &str) -> Result<i32, String> {
match some_parameter {
"This works" => Ok(1),
&_ => Err("An Error".to_string())
}
}
fn main() {
println!("Result: {:#?}", this_an_example("This works"));
println!("Oh no!: {:#?}", this_an_example("Error"));
}

If we want to handle the result type, we use pattern matching. If we don’t use ...