All Posts
RustPatternsError Handling
August 20, 2024

Error Handling Patterns in Rust

Result, Option, the question mark operator, and custom error types -- a practical guide to handling errors the Rust way.

Errors Are Data, Not Exceptions

Rust does not have exceptions. Errors are values returned from functions, forcing you to handle them explicitly. This is not a limitation -- it is a feature.

The Result Type

Result<T, E> is an enum with two variants: Ok(T) for success and Err(E) for failure. Every fallible operation returns a Result, and the compiler ensures you handle both cases.

The Question Mark Operator

The ? operator is syntactic sugar for early return on error. It propagates errors up the call stack without verbose match statements.

Custom Error Types

For libraries, define your own error enum. Implement std::error::Error and Display. Use the thiserror crate to reduce boilerplate.

The Anyhow Pattern

For applications, use the anyhow crate. It provides a catch-all error type with context chaining, perfect for CLI tools and web servers where you need good error messages without complex type hierarchies.

The Takeaway

Rust's error handling is verbose compared to exceptions, but it eliminates an entire class of bugs: unhandled errors. Every failure path is visible in the type signature.

Written by

Shyam