Error Handling in Rust
Recoverable errors with Result, the ? operator, panics for bugs, custom error types, From conversions, thiserror and anyhow, Option/Result combinators, and when unwrap is acceptable.
Rust has no exceptions. Errors are split into two kinds:
| Kind | Mechanism | Examples |
|---|---|---|
| Recoverable | Return a Result<T, E> value | File not found, invalid input, network timeout |
| Unrecoverable (bugs) | panic! — unwind the thread (or abort) | Index out of bounds, broken invariant, unwrap() on None |
Because errors are ordinary return values, the type signature tells you a function can fail, and the compiler warns if you ignore a Result.
Result
enum Result<T, E> {
Ok(T),
Err(E),
}
use std::fs;
fn read_config(path: &str) -> Result<String, std::io::Error> {
fs::read_to_string(path)
}
match read_config("app.toml") {
Ok(text) => println!("{text}"),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => println!("using defaults"),
Err(e) => eprintln!("failed: {e}"),
}The ? operator
Propagating errors with match everywhere is verbose. ? does it for you: on Ok(v) it evaluates to v; on Err(e) it returns early from the function with the error, converting it via From if needed.
use std::fs::File;
use std::io::{self, Read};
fn read_username() -> Result<String, io::Error> {
let mut s = String::new();
File::open("user.txt")?.read_to_string(&mut s)?; // each ? may return early
Ok(s.trim().to_string())
}? also works on Option in functions returning Option (returning None early). main can return Result<(), E> so you can use ? there too.
Custom error types
Libraries should expose precise, matchable errors. A typical pattern is an enum of failure cases:
use std::fmt;
#[derive(Debug)]
enum ConfigError {
Io(std::io::Error),
Parse { line: usize, message: String },
MissingKey(String),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Io(e) => write!(f, "I/O error: {e}"),
ConfigError::Parse { line, message } => write!(f, "line {line}: {message}"),
ConfigError::MissingKey(k) => write!(f, "missing key '{k}'"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<std::io::Error> for ConfigError { // lets ? convert io::Error automatically
fn from(e: std::io::Error) -> Self { ConfigError::Io(e) }
}
fn load(path: &str) -> Result<Config, ConfigError> {
let text = std::fs::read_to_string(path)?; // io::Error → ConfigError::Io
parse(&text)
}thiserror and anyhow
Writing those impls by hand is boilerplate. Two crates are near-universal:
// Libraries: thiserror derives Display, Error and From
#[derive(Debug, thiserror::Error)]
enum ConfigError {
#[error("I/O error")]
Io(#[from] std::io::Error),
#[error("line {line}: {message}")]
Parse { line: usize, message: String },
#[error("missing key '{0}'")]
MissingKey(String),
}
// Applications: anyhow::Result holds any error, with context
use anyhow::{Context, Result, bail};
fn main() -> Result<()> {
let cfg = std::fs::read_to_string("app.toml")
.context("reading app.toml")?; // adds a human-readable layer
if cfg.is_empty() {
bail!("config file is empty");
}
Ok(())
}
// Error: reading app.toml
// Caused by: No such file or directory (os error 2)Rule of thumb: thiserror for libraries (callers need to match on error kinds), anyhow for applications (you mostly report errors).
Combinators
Option and Result have methods that replace many match expressions:
| Method | Does |
|---|---|
map(f) | Transform the success value |
map_err(f) | Transform the error |
and_then(f) | Chain another fallible operation (flatMap) |
ok_or(err) / ok_or_else(f) | Option → Result |
ok() | Result → Option (dropping the error) |
unwrap_or(v) / unwrap_or_else(f) / unwrap_or_default() | Fallback value |
? | Propagate |
let port: u16 = std::env::var("PORT")
.ok() // Option<String>
.and_then(|s| s.parse().ok()) // Option<u16>
.unwrap_or(8080);
let user = users.get(&id).ok_or(ApiError::NotFound(id))?;Panics
panic! signals a bug: a state the program can't sensibly continue from. By default, the panicking thread unwinds (running destructors) and the panic message plus location is printed; in main it ends the process. (panic = "abort" in Cargo.toml aborts immediately instead — smaller binaries.)
let v = vec![1, 2, 3];
v[99]; // panics: index out of bounds
let n: u32 = "abc".parse().unwrap(); // panics with the parse error
let cfg = load().expect("config must be valid at startup"); // panic with a messageWhen unwrap/expect is fine
- Tests and examples.
- When failure is logically impossible and you can explain why in an
expectmessage:"127.0.0.1".parse::<IpAddr>().expect("valid literal IP"). - At startup, when the program can't run without something (fail fast with a clear message).
Avoid them in library code and request-handling paths, where a panic could crash a server thread for one bad input.
- Recoverable errors are Result values; bugs are panics.
- ? propagates errors early and converts them via From.
- Define error enums implementing Display and Error; use thiserror in libraries, anyhow (with context) in apps.
- Combinators (map, and_then, ok_or, unwrap_or) keep handling concise.
- unwrap/expect only in tests, impossible cases, or startup; never on untrusted input paths.