The TooLarge error from the previous lesson says that something was wrong, but not what. A caller who wants to tell a user "you asked for 1200, the limit is 1000", or who wants to reserve the maximum instead, has nothing to work with. An error type can carry the input that broke a rule as fields. Code can then match those fields, and a Display implementation can turn them into a sentence for people.
Those are two audiences with different needs, and Rust keeps them apart. Fields are the stable, machine-readable contract: a caller can compare error.limit without parsing text. The Display message is for humans and may change wording at any time. Implementing std::error::Error on top lets the type travel through standard interfaces such as Box<dyn Error>. The trait has no required methods, but it requires both Debug and Display.
Predict and run
What values will the error contain, and what will it print?
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
struct LimitError { attempted: u32, limit: u32 }
impl fmt::Display for LimitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "quantity {} exceeds {}", self.attempted, self.limit)
}
}
impl std::error::Error for LimitError {}
fn check(value: u32, limit: u32) -> Result<(), LimitError> {
if value > limit {
Err(LimitError { attempted: value, limit })
} else {
Ok(())
}
}
fn main() {
let error = check(11, 10).unwrap_err();
assert_eq!(error.attempted, 11);
println!("{error}");
}Check your prediction
quantity 11 exceeds 10println!("{error}") uses Display, while {error:?} would print LimitError { attempted: 11, limit: 10 }. The formatter f is borrowed mutably, and write! returns fmt::Result; returning that result lets a failing destination report its error. Now change the call to check(11, 11). Predict the outcome before you run it: unwrap_err panics, because the check uses > and a value equal to the limit is accepted. Replace unwrap_err with assert!(check(11, 11).is_ok()) to state that boundary explicitly.
Let the caller act on the fields
Fields earn their place when a caller makes a decision with them. Below, reserve recovers from a limit error by taking the limit instead, without any string handling. The run function shows the other path: ? converts LimitError into Box<dyn Error> automatically, because the standard library implements From for any type that implements Error.
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct LimitError { attempted: u32, limit: u32 }
impl fmt::Display for LimitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "quantity {} exceeds {}", self.attempted, self.limit)
}
}
impl Error for LimitError {}
fn check(value: u32, limit: u32) -> Result<(), LimitError> {
if value > limit { Err(LimitError { attempted: value, limit }) } else { Ok(()) }
}
fn reserve(requested: u32, limit: u32) -> u32 {
match check(requested, limit) {
Ok(()) => requested,
Err(error) => error.limit,
}
}
fn run() -> Result<(), Box<dyn Error>> {
println!("Reserved {}", reserve(14, 10));
check(3, 10)?;
println!("3 fits");
check(12, 10)?;
println!("not reached");
Ok(())
}
fn main() {
if let Err(error) = run() {
println!("Stopped: {error}");
}
}Reserved 10
3 fits
Stopped: quantity 12 exceeds 10The trade-off shows at the boundary. Inside run, the error is now a Box<dyn Error>: convenient, because any error type fits, but the concrete fields are hidden behind the trait object. Library functions should return the concrete type so callers keep the fields. Erase the type only near the top of a program, where all you will do is print it.
One type, several causes
A real update can fail for more than one reason. An enum gives each cause its own variant with its own fields, and one Display implementation matches on them. A caller can still branch on the variant, while code that only prints the error does not care how many variants exist.
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
enum UpdateError {
TooLarge { attempted: u32, limit: u32 },
UnknownItem(String),
}
impl fmt::Display for UpdateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
UpdateError::TooLarge { attempted, limit } => {
write!(f, "quantity {attempted} exceeds {limit}")
}
UpdateError::UnknownItem(name) => write!(f, "unknown item {name:?}"),
}
}
}
impl std::error::Error for UpdateError {}
fn update(item: &str, quantity: u32) -> Result<u32, UpdateError> {
if item != "bolt" && item != "nut" {
return Err(UpdateError::UnknownItem(item.to_string()));
}
if quantity > 1000 {
return Err(UpdateError::TooLarge { attempted: quantity, limit: 1000 });
}
Ok(quantity)
}
fn main() {
for (item, quantity) in [("bolt", 40), ("nut", 1500), ("gear", 3)] {
match update(item, quantity) {
Ok(value) => println!("{item}: {value}"),
Err(UpdateError::TooLarge { limit, .. }) => println!("{item}: capped at {limit}"),
Err(error) => println!("{item}: {error}"),
}
}
}bolt: 40
nut: capped at 1000
gear: unknown item "gear"The caller handles one variant specially and falls back to the message for the rest. If you publish this enum in a library, adding a variant later breaks every caller whose match is exhaustive. Marking the enum #[non_exhaustive] forces callers outside your crate to write a wildcard arm, which keeps future variants a compatible change at the cost of weaker exhaustiveness checking for them.
Mistakes the compiler catches, and one it does not
Forgetting Display fails at the impl Error line:
#[derive(Debug)]
struct Duplicate { id: u32 }
impl std::error::Error for Duplicate {}The compiler reports error[E0277] and says that Duplicate doesn't implement std::fmt::Display. Forgetting the derive gives the matching error for Debug.
Two other mistakes compile. Writing write!(f, "..."); with a semicolon and then Ok(()) throws the formatting result away; the compiler only warns about an unused Result. Worse, writing write!(f, "{self}") inside Display calls the same fmt again, forever, and the program overflows its stack at run time. Format the fields, never self.
Write messages that compose
Start the message in lowercase and leave off the final period, like the standard library does: quantity 12 exceeds 10. Then a caller can embed it in a longer line, such as Stopped: quantity 12 exceeds 10, without awkward punctuation. On Day 5 you will chain one error as the source of another.
Practice
Your turn
Define a Duplicate error carrying a batch ID, with Display printing batch 7 already exists and an Error implementation. Write register(existing: &[u32], id: u32) -> Result<(), Duplicate>. With existing IDs [3, 7], registering 7 must fail with an id field of 7, and registering 9 must succeed. Print the error, then batch 9 registered.
fn main() {
let existing = [3, 7];
let _ = existing;
// Define Duplicate and register, then try 7 and 9.
}Hint 1: the idea
Derive Debug for inspection and implement Display by hand for the human-facing message. The error stores the ID so a caller can read it without parsing the text.
Hint 2: a first step
Inside register, existing.contains(&id) tells you whether to return Err(Duplicate { id }). In main, use unwrap_err() on the first call and assert on error.id.
Worked solution
use std::fmt;
#[derive(Debug)]
struct Duplicate { id: u32 }
impl fmt::Display for Duplicate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "batch {} already exists", self.id)
}
}
impl std::error::Error for Duplicate {}
fn register(existing: &[u32], id: u32) -> Result<(), Duplicate> {
if existing.contains(&id) { Err(Duplicate { id }) } else { Ok(()) }
}
fn main() {
let existing = [3, 7];
let error = register(&existing, 7).unwrap_err();
assert_eq!(error.id, 7);
println!("{error}");
register(&existing, 9).expect("9 is new");
println!("batch 9 registered");
}batch 7 already exists
batch 9 registeredThe assertion reads error.id directly, so a later change to the message wording cannot break it. That is the point of keeping fields: tests and callers depend on data, people read the text. Day 4 uses the same idea for duplicate retries, where the stored ID decides whether a repeat is a replay or a conflict.
Completion is saved in this browser only. It does not measure mastery.