Programming languages · Intermediate · 22 min
Handle errors in Rust with Result, ? and thiserror
By Padding · Updated 18 Nov 2026
Debian 13 (rust:1.100 image) · Rust 1.100.0 · thiserror 2.0.21 · anyhow 1.0.105
You will turn a Rust 1.100 config reader that panics on bad input into one that returns typed errors from a thiserror library and reports the file, the line and the cause through anyhow.
On this page
Rust has no exceptions. A function that can fail says so in its return type: Result<T, E> holds either a value (Ok) or an error (Err), and Option<T> holds either a value (Some) or nothing (None). The compiler will not let you use the value inside until you have decided what happens in the other case.
The quickest decision is .unwrap(), which takes the value out or stops the program. Tutorials and examples are full of it, and so is a lot of real code that crashes on the first unexpected input. This tutorial starts from exactly that kind of program and replaces every unwrap, one technique at a time.
The program is limits, a small tool that reads settings such as max_upload_mb = 25 from a config file. By the end it is split into a library with its own error type, built with the thiserror crate, and a binary that uses anyhow to add context. When something goes wrong, it prints the file, the line and the underlying reason, then exits with a non-zero code a script can check.
Everything here was written for Rust 1.100.0, thiserror 2.0.21 and anyhow 1.0.105. Any Rust from 1.85 onwards (the 2024 edition) runs the code.
Step 1 · Write the unwrap version and watch it panic
Create a throwaway folder and a new binary crate:
mkdir -p ~/rust-errors-demo
cd ~/rust-errors-demo
cargo new limits
cd limitsAdd two config files to practise on: one valid, and one where a teammate typed a word instead of a number on line 3:
cat > app.conf <<'CONF'
# upload limits for the photo service
max_upload_mb = 25
max_files = 10
timeout_secs = 30
CONF
cat > bad.conf <<'CONF'
# upload limits for the photo service
max_upload_mb = 25
max_files = ten
timeout_secs = 30
CONFNow the first version of the program. It takes the file name from the command line, reads the file, skips blank lines and comments, splits each line at = and parses the right-hand side as a whole number. Four things can fail, and each one is handled with unwrap:
cat > src/main.rs <<'RS'
use std::env;
use std::fs;
fn main() {
let path = env::args().nth(1).unwrap();
let text = fs::read_to_string(&path).unwrap();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) = line.split_once('=').unwrap();
let number: u32 = value.trim().parse().unwrap();
println!("{} = {}", key.trim(), number);
}
}
RS
cargo build --quiet
./target/debug/limits app.confThe four calls that can fail return two different types:
env::args().nth(1)returns anOption<String>:Noneif you gave no argument.fs::read_to_stringreturns aResult<String, io::Error>: an error if the file is missing or unreadable.split_once('=')returns anOption<(&str, &str)>:Noneif the line has no=.parse()returns aResult<u32, ParseIntError>: an error if the text is not a whole number that fits in au32.
Now give it bad input three ways. || echo prints the exit code, because a program that panics does not end normally:
./target/debug/limits missing.conf || echo "exit code: $?"
./target/debug/limits bad.conf || echo "exit code: $?"
./target/debug/limits || echo "exit code: $?"Each run stops with a panic. The message names the source line of the unwrap that failed, something like thread 'main' (1234) panicked at src/main.rs:6:42: (the number in brackets is the thread ID, which changes from run to run), followed by the error's debug form, such as `called `Result::unwrap() on an Err value: Os { code: 2, kind: NotFound, message: "No such file or directory" }`. The bad number gives `ParseIntError { kind: InvalidDigit }, and the missing argument gives `called `Option::unwrap() on a None value``. None of these tell the person running the tool which file or which config line was wrong.
A panic is Rust's way of saying "this should never happen": it prints the message, unwinds the thread and exits with code 101. Ask for a backtrace to see the chain of function calls that led there:
RUST_BACKTRACE=1 ./target/debug/limits missing.conf 2> trace.txt || echo "exit code: $?"
head -n 15 trace.txtCheck it worked
./target/debug/limits app.conf prints three lines: max_upload_mb = 25, max_files = 10 and timeout_secs = 30. Each bad run prints a panicked at src/main.rs message and then exit code: 101. trace.txt starts with the same panic message, followed by a stack backtrace: line and numbered frames.
Step 2 · Handle each case with match and if let
match makes you write an arm for every variant, and if let handles one variant and lets you put the rest in an else. Replace main.rs with a version that handles all four failures itself:
cat > src/main.rs <<'RS'
use std::env;
use std::fs;
use std::process;
fn main() {
let path = match env::args().nth(1) {
Some(path) => path,
None => {
eprintln!("usage: limits <config-file>");
process::exit(2);
}
};
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(err) => {
eprintln!("could not read {path}: {err}");
process::exit(1);
}
};
for (index, line) in text.lines().enumerate() {
let line_no = index + 1;
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((key, value)) = line.split_once('=') {
let value = value.trim();
match value.parse::<u32>() {
Ok(number) => println!("{} = {}", key.trim(), number),
Err(err) => eprintln!("{path}:{line_no}: {value:?} is not a whole number: {err}"),
}
} else {
eprintln!("{path}:{line_no}: expected key = value");
}
}
}
RS
cargo build --quiet
./target/debug/limits bad.conf; echo "exit code: $?"
./target/debug/limits missing.conf || echo "exit code: $?"What changed:
eprintln!writes to standard error rather than standard output, so error messages do not end up mixed into output that another program reads.process::exit(2)for a usage mistake andprocess::exit(1)for a failure give scripts an exit code to check.enumerate()counts lines from 0, soindex + 1is the line number a person sees in their editor.{err}prints the error'sDisplayform, the readable sentence, and{value:?}prints the value in quotes, so a stray space or an empty value shows up clearly.
The messages are now useful. The structure is not. All the error handling sits inside main, mixed into the logic, and a bad line is reported but skipped: the program carries on and exits with code 0, so a script that runs it believes the config loaded. Nothing else can reuse this parsing code either.
Check it worked
The bad.conf run prints max_upload_mb = 25 and timeout_secs = 30, plus bad.conf:3: "ten" is not a whole number: invalid digit found in string, then exit code: 0. That zero is the problem the next step fixes. The missing.conf run prints could not read missing.conf: No such file or directory (os error 2) and exit code: 1.
Step 3 · Return a Result and pass errors up with ?
Move the parsing into a function that returns Result, so the caller decides what to do with a failure. The function can fail in three ways, so give it an error type with one variant for each: an enum. For ? to work with it, the enum needs From conversions from the standard library's error types:
cat > src/main.rs <<'RS'
use std::env;
use std::fmt;
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::process;
#[derive(Debug)]
enum ConfigError {
Io(io::Error),
Parse(ParseIntError),
Syntax,
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Io(err) => write!(f, "could not read the file: {err}"),
ConfigError::Parse(err) => write!(f, "bad number: {err}"),
ConfigError::Syntax => write!(f, "expected key = value"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<io::Error> for ConfigError {
fn from(err: io::Error) -> Self {
ConfigError::Io(err)
}
}
impl From<ParseIntError> for ConfigError {
fn from(err: ParseIntError) -> Self {
ConfigError::Parse(err)
}
}
fn load(path: &str) -> Result<Vec<(String, u32)>, ConfigError> {
let text = fs::read_to_string(path)?;
let mut settings = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) = line.split_once('=').ok_or(ConfigError::Syntax)?;
let number: u32 = value.trim().parse()?;
settings.push((key.trim().to_string(), number));
}
Ok(settings)
}
fn main() {
let Some(path) = env::args().nth(1) else {
eprintln!("usage: limits <config-file>");
process::exit(2);
};
match load(&path) {
Ok(settings) => {
for (key, value) in &settings {
println!("{key} = {value}");
}
}
Err(err) => {
eprintln!("error: {err}");
process::exit(1);
}
}
}
RS
cargo build --quiet
./target/debug/limits app.conf
./target/debug/limits bad.conf || echo "exit code: $?"
./target/debug/limits missing.conf || echo "exit code: $?"The ? after a call does three things. On Ok it unwraps the value and carries on. On Err it returns from load straight away. And before returning, it converts the error into the function's own error type by calling From::from. That is why fs::read_to_string(path)? can return an io::Error from a function declared to return ConfigError: the From<io::Error> implementation tells Rust how.
? only works on a Result inside a function that returns Result, or on an Option inside one that returns Option. split_once gives an Option, so .ok_or(ConfigError::Syntax) turns None into an Err first.
In main, let ... else is a shorter match for the case where you want one variant and must leave the function on any other: if nth(1) is None, the else block runs and has to exit, return or panic.
The parsing loop now reads like the happy path, and a bad file stops the program with exit code 1. But the Display and From implementations are mostly boilerplate, and the messages have lost the line number.
Check it worked
app.conf still prints its three settings. bad.conf prints only error: bad number: invalid digit found in string and exit code: 1, with no partial output. missing.conf prints error: could not read the file: No such file or directory (os error 2) and exit code: 1.
Step 4 · Generate the error boilerplate with thiserror
thiserror is a crate that writes the Display, Error and From implementations for you from attributes on the enum. It adds nothing to your program at run time; the generated code is the same as what you wrote by hand. Add it:
cargo add thiserror@2.0.21The first build downloads thiserror and the handful of small crates its code generator uses. On metered or prepaid data, that happens once per machine; later projects reuse the copies in ~/.cargo/registry.
Replace everything above fn load in main.rs. The load and main functions stay exactly as they were:
cat > src/main.rs <<'RS'
use std::env;
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::process;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("could not read the file: {0}")]
Io(#[from] io::Error),
#[error("bad number: {0}")]
Parse(#[from] ParseIntError),
#[error("expected key = value")]
Syntax,
}
fn load(path: &str) -> Result<Vec<(String, u32)>, ConfigError> {
let text = fs::read_to_string(path)?;
let mut settings = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) = line.split_once('=').ok_or(ConfigError::Syntax)?;
let number: u32 = value.trim().parse()?;
settings.push((key.trim().to_string(), number));
}
Ok(settings)
}
fn main() {
let Some(path) = env::args().nth(1) else {
eprintln!("usage: limits <config-file>");
process::exit(2);
};
match load(&path) {
Ok(settings) => {
for (key, value) in &settings {
println!("{key} = {value}");
}
}
Err(err) => {
eprintln!("error: {err}");
process::exit(1);
}
}
}
RS
cargo build --quiet
./target/debug/limits bad.conf || echo "exit code: $?"#[derive(Error)]implementsstd::error::Error.#[error("...")]on each variant becomes itsDisplaytext.{0}is the variant's first field.#[from]generates theFromimplementation you wrote by hand, and also marks that field as the error's source: the lower-level error that caused it. Anything that walks the chain of causes, as anyhow does later, can find it throughError::source().
Putting {0} in the message and also marking the field as the source means the cause appears twice once something prints the whole chain. The next step drops it from the message.
Check it worked
Cargo.toml now has thiserror = "2.0.21" under [dependencies]. The bad.conf run prints the same error: bad number: invalid digit found in string and exit code: 1 as before, from about 20 fewer lines of code.
Step 5 · Move the parser into a library with line numbers in its errors
A library is code other programs call. Its errors should be types the caller can inspect, and each variant should carry the details a person needs to fix the problem: here, the file for a read error and the line number for everything else.
A From conversion cannot add those details, because ParseIntError knows nothing about line numbers. Use map_err instead: it changes the error inside an Err with a closure and leaves an Ok alone. ok_or_else does the same for None.
Cargo treats src/lib.rs as the library and src/main.rs as a binary that uses it, both in one package called limits. Create the library:
cat > src/lib.rs <<'RS'
//! Reads `key = number` settings from a small config file.
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::path::{Path, PathBuf};
use thiserror::Error;
/// Everything that can go wrong while loading settings.
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("could not read {}", .path.display())]
Read { path: PathBuf, source: io::Error },
#[error("line {line}: expected `key = value`, found {text:?}")]
Syntax { line: usize, text: String },
#[error("line {line}: {value:?} is not a whole number")]
BadNumber {
line: usize,
value: String,
source: ParseIntError,
},
}
/// Parses settings from text. Blank lines and lines starting with # are skipped.
pub fn parse(text: &str) -> Result<Vec<(String, u32)>, ConfigError> {
let mut settings = Vec::new();
for (index, raw) in text.lines().enumerate() {
let line = index + 1;
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let (key, value) = trimmed
.split_once('=')
.ok_or_else(|| ConfigError::Syntax {
line,
text: trimmed.to_string(),
})?;
let value = value.trim();
let number = value
.parse::<u32>()
.map_err(|source| ConfigError::BadNumber {
line,
value: value.to_string(),
source,
})?;
settings.push((key.trim().to_string(), number));
}
Ok(settings)
}
/// Reads the file at `path` and parses it.
pub fn load(path: &Path) -> Result<Vec<(String, u32)>, ConfigError> {
let text = fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_path_buf(),
source,
})?;
parse(&text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_settings_and_skips_comments() {
let settings = parse("# limits\nmax_files = 10\n\nmax_upload_mb = 25\n").unwrap();
assert_eq!(
settings,
vec![
("max_files".to_string(), 10),
("max_upload_mb".to_string(), 25)
]
);
}
#[test]
fn reports_the_line_of_a_bad_number() {
let err = parse("max_files = 10\nmax_upload_mb = lots\n").unwrap_err();
assert!(matches!(err, ConfigError::BadNumber { line: 2, .. }));
}
}
RSPoints to notice:
- The variants are structs with named fields, so the messages can use
{line}and{value:?}directly.PathBufhas noDisplay, so theReadmessage calls.path.display(); the leading dot refers to a field. - A field named
sourceis the error's source automatically, as if marked#[source]. The messages no longer repeat the cause; the chain carries it. parsetakes text andloadtakes a path, so the tests check the parsing rules without creating files.unwrapandunwrap_errare fine in tests. A panic is exactly how a Rust test reports failure.lines()also strips the carriage return at the end of each line, so a file saved with Windows line endings parses the same way.
Replace main.rs with a thin binary that calls the library by the package name, limits::load:
cat > src/main.rs <<'RS'
use std::env;
use std::path::PathBuf;
use std::process;
fn main() {
let Some(arg) = env::args_os().nth(1) else {
eprintln!("usage: limits <config-file>");
process::exit(2);
};
let path = PathBuf::from(arg);
match limits::load(&path) {
Ok(settings) => {
for (key, value) in &settings {
println!("{key} = {value}");
}
}
Err(err) => {
eprintln!("error: {err}");
process::exit(1);
}
}
}
RS
printf 'max_files = 10\ntimeout_secs 30\n' > typo.conf
cargo test --quiet
cargo build --quiet
./target/debug/limits bad.conf || echo "exit code: $?"
./target/debug/limits typo.conf || echo "exit code: $?"args_os returns the argument as an OsString instead of a String, so a file name that is not valid UTF-8 cannot panic the program before it starts.
Check it worked
cargo test prints test result: ok. 2 passed. bad.conf gives error: line 3: "ten" is not a whole number and typo.conf gives `error: line 2: expected `key = value, found "timeout_secs 30"`, each followed by `exit code: 1. The line numbers are back, but printing only the top error has dropped the reason (invalid digit found in string), and the parse errors do not name the file.
Step 6 · Add context in the binary with anyhow
An application rarely needs to match on error types. It needs to stop, say clearly what it was doing, and show the whole chain of causes. anyhow provides one error type, anyhow::Error, that can hold any error, plus a Context trait for wrapping an error in a sentence about what was being attempted. Add it to the package:
cargo add anyhow@1.0.105Replace main.rs:
cat > src/main.rs <<'RS'
use std::env;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
fn main() -> Result<()> {
let Some(arg) = env::args_os().nth(1) else {
bail!("usage: limits <config-file>");
};
let path = PathBuf::from(arg);
let settings = limits::load(&path)
.with_context(|| format!("could not load settings from {}", path.display()))?;
for (key, value) in &settings {
println!("{key} = {value}");
}
let upload = settings
.iter()
.find(|(key, _)| key == "max_upload_mb")
.map(|(_, value)| *value)
.context("max_upload_mb is missing")?;
println!("Uploads are limited to {upload} MB.");
Ok(())
}
RS
printf 'max_files = 3\n' > small.conf
cargo build --quiet
./target/debug/limits app.conf
./target/debug/limits bad.conf || echo "exit code: $?"
./target/debug/limits missing.conf || echo "exit code: $?"
./target/debug/limits small.conf || echo "exit code: $?"How it fits together:
anyhow::Result<()>is short forResult<(), anyhow::Error>. Whenmainreturns anErr, Rust prints `Error: ` followed by the error's debug form and exits with code 1. anyhow's debug form is the full chain.with_contextwraps the library'sConfigErrorin a message that names the file. The closure only runs on failure, so theformat!costs nothing when loading works. Use.context("fixed text")when the message needs no formatting.?then converts the wrapped error intoanyhow::Error. That works for any error type that implementsstd::error::Error, which thiserror gaveConfigError.Contextalso works onOption:.context("max_upload_mb is missing")?turnsNoneinto an error with that message.bail!returns early with a new error made from a message.
The library still knows nothing about anyhow. Code that calls limits::load gets a ConfigError it can match on, like the test in the previous step.
Check it worked
app.conf prints its three settings and Uploads are limited to 25 MB. The bad.conf run prints the file, the line and the reason, then exit code: 1:
Error: could not load settings from bad.conf
Caused by:
0: line 3: "ten" is not a whole number
1: invalid digit found in stringmissing.conf shows the same shape, ending in No such file or directory (os error 2). small.conf prints max_files = 3, then Error: max_upload_mb is missing and exit code: 1.
Step 7 · Use expect where a failure is a bug, then clean up
Not every unwrap is wrong. The question to ask is whose mistake a failure would be. Input from outside the program (files, arguments, the network, other people's data) can be wrong at any time, so it gets a Result. A value the program controls, which can only be wrong if the code itself has a bug, can panic. For those cases, use expect with a message that says what you assumed, so the panic explains itself.
Give limits built-in defaults for when no file is given. The defaults are written in the source code, so if they fail to parse, that is a bug to fix, not a user error to report:
cat > src/main.rs <<'RS'
use std::env;
use std::path::PathBuf;
use anyhow::{Context, Result};
/// Used when no config file is given. Written by us, so a parse failure is a bug.
const DEFAULTS: &str = "max_upload_mb = 25\nmax_files = 10\ntimeout_secs = 30\n";
fn main() -> Result<()> {
let settings = match env::args_os().nth(1) {
Some(arg) => {
let path = PathBuf::from(arg);
limits::load(&path)
.with_context(|| format!("could not load settings from {}", path.display()))?
}
None => limits::parse(DEFAULTS).expect("the built-in DEFAULTS should always parse"),
};
for (key, value) in &settings {
println!("{key} = {value}");
}
let upload = settings
.iter()
.find(|(key, _)| key == "max_upload_mb")
.map(|(_, value)| *value)
.context("max_upload_mb is missing")?;
println!("Uploads are limited to {upload} MB.");
Ok(())
}
RS
cargo build --quiet
./target/debug/limits
./target/debug/limits bad.conf || echo "exit code: $?"The rule of thumb that most Rust projects follow:
- Libraries use thiserror. Callers need an error type they can match on, as the test did with
ConfigError::BadNumber { line: 2, .. }, and the error type is part of the library's public API. - Applications use anyhow. The binary's job is to stop and explain, so one error type with context and a printed chain is enough.
- Panics are for bugs. Use
expectwith a reason for things the program guarantees, andunwrapin tests and throwaway experiments. Never let input from outside reach anunwrap.
When you are done, remove the demo folder:
cd ~
rm -rf ~/rust-errors-demoCheck it worked
Running limits with no argument prints the three default settings and Uploads are limited to 25 MB., where the previous version printed a usage error. bad.conf, run before the clean-up, still prints the full Caused by: chain and exit code: 1. After the clean-up, ls ~/rust-errors-demo reports No such file or directory.
Next steps
- Turn
limitsinto a proper command-line tool with flags, help text and exit codes: Build a command-line tool in Rust with clap. - Get comfortable with the borrow checker that decided some of the
&strandStringchoices here: Understand Rust ownership by fixing borrow checker errors. - Compare Rust's approach with Go's, where errors are also values but wrapping is done by hand: Handle errors the Go way.
- Put the library and the binary in separate crates as the project grows: Split a Rust project into a Cargo workspace.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials