thiserror
Custom error types.
thiserror is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Custom Errors?
Libraries should expose meaningful error types so callers can react to specific failures. Writing these by hand means lots of boilerplate. The thiserror crate generates it for you.
Adding thiserror
Add it as a dependency. It is a derive-macro crate with zero runtime cost.
[dependencies]
thiserror = "1.0"Defining an Error Enum
Derive Error on an enum where each variant is a distinct failure. The #[error("...")] attribute provides the Display message.
use thiserror::Error;
#[derive(Error, Debug)]
pub enum DataError {
#[error("item not found")]
NotFound,
#[error("invalid input: {0}")]
Invalid(String),
}Interpolating Fields
The message string can reference named or positional fields, so error text carries context.
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ConfigError {
#[error("missing key: {key}")]
Missing { key: String },
#[error("value {0} out of range")]
OutOfRange(i32),
}Automatic Display and Error
The derive implements both Display (from your messages) and std::error::Error automatically. No manual impl blocks needed.
Wrapping a Source Error
#[from] generates a From impl so the ? operator can convert an underlying error into your type. #[source] marks the cause.
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("io failure")]
Io(#[from] std::io::Error),
#[error("parse failure")]
Parse(#[from] std::num::ParseIntError),
}Using It with ?
Thanks to #[from], the ? operator auto-converts standard errors into your AppError.
fn read_number(path: &str) -> Result<i32, AppError> {
let text = std::fs::read_to_string(path)?; // io::Error -> AppError
let n: i32 = text.trim().parse()?; // ParseIntError -> AppError
Ok(n)
}The source Chain
When you wrap an error, thiserror exposes the cause through Error::source, enabling full error chains for logging and debugging.
transparent Errors
#[error(transparent)] forwards both Display and source to the wrapped error, useful for a pass-through variant.
use thiserror::Error;
#[derive(Error, Debug)]
pub enum WrapError {
#[error(transparent)]
Other(#[from] std::io::Error),
}When to Use thiserror
Reach for thiserror when:
- You are writing a library
- Callers need to match on specific error variants
- You want a stable, typed error API
For applications where you just want to bubble errors up, anyhow is often simpler.
Matching on Variants
Because the error is a real enum, callers can match on it to react differently to each failure kind.
fn handle(err: AppError) {
match err {
AppError::Io(_) => println!("retry the file operation"),
AppError::Parse(_) => println!("ask the user to fix input"),
}
}Quick Check
What does the #[from] attribute generate in a thiserror enum?
Recap
You learned the thiserror crate:
#[derive(Error)]generates Display and Error impls#[error("...")]defines messages with field interpolation#[from]enables?conversion from source errorstransparentforwards to a wrapped error- Ideal for typed library error APIs
Frequently asked questions
Is the “thiserror” lesson free?
Yes — the full text of “thiserror” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “thiserror”?
Custom error types. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “thiserror” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.