The Analogy: The Fault Report's Four Audiences
A mechanic finds a failed seal on the number two hydraulic pump and writes exactly that. The note is specific, unambiguous, and completely useless to a passenger standing at the gate. It is also not a decision: the mechanic has no idea whether a spare airframe is parked two gates away, whether the flight is the last of the day, or whether ninety of the passengers are connecting. So they write down precisely what they found and hand it upward. That is a leaf function returning a specific error -- exact about the fact, and deliberately silent about what to do.
Each level above restates it in its own vocabulary and adds the one thing only that level knows. Maintenance control knows the parts inventory, so "number two pump seal" becomes "unserviceable, four hours". The duty manager knows the fleet, so four hours becomes "swap the airframe, depart from stand 41". The gate agent knows the passengers, so that becomes an announcement. Every restatement drops detail on purpose, because detail the audience cannot act on is noise -- and every restatement also adds something, which is the entire reason the chain exists rather than piping the mechanic's note straight to the departure board.
The decision is made exactly once, at the first level that has enough context, and everybody below is forbidden from pre-empting it. A mechanic who started announcing cancellations would be wrong most of the time -- not through carelessness, but because the information that would make them right lives two levels up. This is the whole argument for propagating rather than handling: the function that detects a problem is very rarely the function that knows what to do about it.
What the chain must not do is lose the original. The announcement says "a technical issue"; the seal failure is still in the maintenance log, and when the same seal fails three times in a month somebody can find that out. An error type that throws away its cause at each hop leaves you with a polished top-level message and no route back to the fact. Keeping the cause is a design requirement, not a nicety.
Syntax or Core Structure
Propagation is one line: match the Result, and on Err, return it.
fn digits(text: &str) -> Result<u32, String> {
match text.parse::<u32>() {
Ok(n) => Ok(n),
Err(_) => Err(format!("{text:?} is not a number")),
}
}
fn doubled(text: &str) -> Result<u32, String> {
let n = match digits(text) {
Ok(n) => n,
Err(e) => return Err(e),
};
Ok(n * 2)
}
fn quadrupled(text: &str) -> Result<u32, String> {
let n = match doubled(text) {
Ok(n) => n,
Err(e) => return Err(e),
};
Ok(n * 2)
}
fn main() {
for text in ["7", "seven"] {
match quadrupled(text) {
Ok(n) => println!("{text:>7} -> {n}"),
Err(e) => println!("{text:>7} -> error: {e}"),
}
}
}
Output:
7 -> 28
seven -> error: "seven" is not a number
The error crossed two function boundaries without changing, and the only function that made a decision was main. Neither doubled nor quadrupled could have decided anything useful: they do not know whether the text came from a config file, a form field or a test, and the right response differs in all three cases.
Read the two propagation blocks again, though. Err(e) => return Err(e) unwraps a value out of one Result and immediately puts it back into an identical one. It is four lines of pure ceremony, it appears twice in a nine-line program, and in a real codebase it appears everywhere. That is the problem the next lesson solves in one character. This lesson is about the part of propagation that is not ceremony -- deciding where errors should be handled, and what has to happen to their types on the way up.
(digits has a related wart: Ok(n) => Ok(n) rebuilds a variant that was already correct. map_err collapses that whole match into one call, and it takes a closure, so it waits for Module 7.)
Technical Depth: The Problem Propagation Creates
One function, two error types
The moment a function calls two things that fail differently, propagation stops being mechanical. A function that parses a number and checks a range has a ParseIntError from one and something of its own from the other, and its signature only has room for one E. There are three ways out, and they are not interchangeable.
| Strategy | Return type | Right for |
|---|---|---|
| One owned enum per layer | Result<T, ConfigError> | libraries; the caller can match on variants |
| A boxed trait object | Result<T, Box<dyn Error>> | binaries and prototypes; the caller can print, little else |
| A string | Result<T, String> | scripts only; the cause is gone for good |
The third row is what the previous lessons used, deliberately, because it keeps examples short. It is also the one that fails the analogy's last paragraph: once a ParseIntError has been rendered into a sentence, nothing downstream can ask whether it was an empty string or an overflow.
From, and the conversion ? will need
The first strategy needs a way to turn a ParseIntError into your enum. Implementing From gives you that, and it is worth doing by hand now because the next lesson's operator calls it for you invisibly.
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Parse(ParseIntError),
Range { got: u32, max: u32 },
}
impl From<ParseIntError> for AppError {
fn from(cause: ParseIntError) -> AppError {
AppError::Parse(cause)
}
}
fn bounded(text: &str, max: u32) -> Result<u32, AppError> {
let n = match text.parse::<u32>() {
Ok(n) => n,
Err(e) => return Err(AppError::from(e)),
};
if n > max {
return Err(AppError::Range { got: n, max });
}
Ok(n)
}
fn describe(e: &AppError) -> String {
match e {
AppError::Parse(cause) => format!("not a number ({cause})"),
AppError::Range { got, max } => format!("{got} is above the limit of {max}"),
}
}
fn main() {
for text in ["40", "0", "41", "forty"] {
match bounded(text, 40) {
Ok(n) => println!("{text:>5} ok {n}"),
Err(e) => println!("{text:>5} error {}", describe(&e)),
}
}
}
Output:
40 ok 40
0 ok 0
41 error 41 is above the limit of 40
forty error not a number (invalid digit found in string)
AppError::Parse keeps the whole ParseIntError, so the top-level message can print the library's own wording without bounded having to guess at it. That is the "keep the cause" requirement satisfied by a single field.
The limitation of From is worth understanding before you rely on it: it receives only the error value. It cannot know which key was being parsed, which line the text came from, or which of two parse calls in the same function failed. A conversion that needs any of that has to be written at the call site instead, against a variant that has somewhere to put it:
Err(e) => {
return Err(AppError::BadField {
field: "workers",
cause: e,
})
}
So the rule of thumb is: write a From impl when the conversion is genuinely context-free, and convert by hand when it is not. A From impl that invents a placeholder for the context it cannot see -- a key field set to "unknown" -- is worse than no impl at all, because now every error claims to carry a key and none of them do.
The escape hatch: Box<dyn Error>
When you do not want to define an enum, you can box whatever comes along. Every error type in the standard library implements the Error trait, and a Box<dyn Error> accepts any of them.
use std::error::Error;
fn ratio(top: &str, bottom: &str) -> Result<f64, Box<dyn Error>> {
let t: u32 = match top.parse() {
Ok(n) => n,
Err(e) => return Err(Box::new(e)),
};
let b: f64 = match bottom.parse() {
Ok(n) => n,
Err(e) => return Err(Box::new(e)),
};
Ok(t as f64 / b)
}
fn main() {
let cases = [("10", "4"), ("ten", "4"), ("10", "four")];
for (top, bottom) in cases {
match ratio(top, bottom) {
Ok(v) => println!("{top:>4} / {bottom:<4} = {v}"),
Err(e) => println!("{top:>4} / {bottom:<4} ! {e}"),
}
}
}
Output:
10 / 4 = 2.5
ten / 4 ! invalid digit found in string
10 / four ! invalid float literal
Two different concrete error types -- ParseIntError and ParseFloatError -- left through one return type, and main printed both without knowing which was which. What you gave up is exactly that: the caller cannot match on variants, cannot ask "was this the numerator or the denominator", and can only print. Module 6 covers the Error trait properly, including downcast_ref for recovering the concrete type, and Module 8 covers why threads want Box<dyn Error + Send + Sync> instead. As a rule: fine in a binary, questionable in a library's public signature.
Adding context on the way up
This is the analogy's second paragraph in code. A leaf function that validates one field cannot know which line or column it came from, so it does not try; the layer that iterates knows both, so it wraps.
#[derive(Debug)]
enum FieldError {
Empty,
NotANumber,
TooBig { got: u32, max: u32 },
}
#[derive(Debug)]
struct LineError {
line: usize,
field: String,
cause: FieldError,
}
fn field(text: &str, max: u32) -> Result<u32, FieldError> {
if text.is_empty() {
return Err(FieldError::Empty);
}
let n = match text.parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(FieldError::NotANumber),
};
if n > max {
return Err(FieldError::TooBig { got: n, max });
}
Ok(n)
}
fn row(line: usize, text: &str) -> Result<u32, LineError> {
let mut total = 0;
for (column, part) in text.split(',').enumerate() {
match field(part.trim(), 100) {
Ok(n) => total += n,
Err(cause) => {
return Err(LineError {
line,
field: format!("column {}", column + 1),
cause,
})
}
}
}
Ok(total)
}
fn explain(cause: &FieldError) -> String {
match cause {
FieldError::Empty => String::from("was blank"),
FieldError::NotANumber => String::from("was not a number"),
FieldError::TooBig { got, max } => format!("was {got}, above the limit of {max}"),
}
}
fn main() {
let rows = ["10, 20, 30", "5,,7", "1, 2, x", "40, 200"];
for (i, text) in rows.into_iter().enumerate() {
match row(i + 1, text) {
Ok(total) => println!("line {} total {total}", i + 1),
Err(e) => println!("line {} {} {}", e.line, e.field, explain(&e.cause)),
}
}
}
Output:
line 1 total 60
line 2 column 2 was blank
line 3 column 3 was not a number
line 4 column 2 was 200, above the limit of 100
FieldError has no line field and never will, because field is the wrong place to know about lines -- the same function should be usable for a command-line flag or a form field. LineError holds the FieldError rather than a rendered sentence, which is what lets main choose the wording. Reverse that -- store cause: String -- and field has to decide how the message reads for every future caller.
Where propagation stops
Somebody has to stop passing it up. The list of levels that qualify is short, and it is short for the same reason in every case: they are the only levels that know something the ones below do not.
| Level | Why it is the right place to stop |
|---|---|
main | there is nothing above it; return a Result and let the exit status carry it |
| A request handler | it knows the response format, so it can turn an error into a status code |
| A retry loop | it knows how many attempts are left and how long to wait |
| A supervisor over independent items | it can record one failure and carry on with the rest |
Everything below one of those propagates. If you find a function handling an error and it is not on that list, the usual explanation is that the error was easier to swallow than to add to a signature.
Real World Example: A Stock Import With Three Layers
A stock file arrives as lines of sku, quantity, unit. Three functions, three vocabularies: unit_grams knows units and nothing else, parse_record knows fields, and import knows rows. Only one of them recovers from anything.
#[derive(Debug)]
enum RecordError {
WrongFieldCount { got: usize, want: usize },
BadQuantity(String),
UnknownUnit(String),
Comment,
}
#[derive(Debug)]
struct ImportError {
row: usize,
text: String,
cause: RecordError,
}
struct Record {
sku: String,
quantity: u32,
grams: u32,
}
fn unit_grams(unit: &str) -> Result<u32, RecordError> {
match unit {
"g" => Ok(1),
"kg" => Ok(1000),
"t" => Ok(1_000_000),
other => Err(RecordError::UnknownUnit(other.to_string())),
}
}
fn parse_record(text: &str) -> Result<Record, RecordError> {
let trimmed = text.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
return Err(RecordError::Comment);
}
let mut parts: Vec<&str> = Vec::new();
for part in trimmed.split(',') {
parts.push(part.trim());
}
if parts.len() != 3 {
return Err(RecordError::WrongFieldCount {
got: parts.len(),
want: 3,
});
}
let quantity = match parts[1].parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(RecordError::BadQuantity(parts[1].to_string())),
};
let per_unit = match unit_grams(parts[2]) {
Ok(g) => g,
Err(e) => return Err(e),
};
Ok(Record {
sku: parts[0].to_string(),
quantity,
grams: quantity * per_unit,
})
}
fn import(lines: &[&str]) -> Result<Vec<Record>, ImportError> {
let mut records = Vec::new();
for (i, line) in lines.iter().copied().enumerate() {
match parse_record(line) {
Ok(r) => records.push(r),
Err(RecordError::Comment) => continue,
Err(cause) => {
return Err(ImportError {
row: i + 1,
text: line.to_string(),
cause,
})
}
}
}
Ok(records)
}
fn explain(cause: &RecordError) -> String {
match cause {
RecordError::WrongFieldCount { got, want } => {
format!("{got} fields, expected {want}")
}
RecordError::BadQuantity(text) => format!("quantity {text:?} is not a number"),
RecordError::UnknownUnit(unit) => format!("unit {unit:?} is not one of g, kg, t"),
RecordError::Comment => String::from("blank or comment"),
}
}
fn main() {
let good = [
"# sku, quantity, unit",
"bolt-m6, 500, g",
"",
"cable-2m, 12, kg",
"plate-a, 3, t",
];
let bad = ["bolt-m6, 500, g", "cable-2m, twelve, kg", "plate-a, 3, t"];
let worse = ["bolt-m6, 500, g", "plate-a, 3, stone"];
let shortest = ["bolt-m6, 500"];
let batches: [(&str, &[&str]); 4] = [
("good ", &good),
("bad ", &bad),
("worse ", &worse),
("shortest", &shortest),
];
for (name, lines) in batches {
match import(lines) {
Ok(records) => {
let mut items = 0;
let mut grams = 0;
let mut names = String::new();
for r in &records {
items += r.quantity;
grams += r.grams;
if !names.is_empty() {
names.push(' ');
}
names.push_str(&r.sku);
}
println!("{name} {items} items, {grams} g [{names}]");
}
Err(e) => println!(
"{name} row {} rejected: {} -- {:?}",
e.row,
explain(&e.cause),
e.text
),
}
}
}
Output:
good 515 items, 3012500 g [bolt-m6 cable-2m plate-a]
bad row 2 rejected: quantity "twelve" is not a number -- "cable-2m, twelve, kg"
worse row 2 rejected: unit "stone" is not one of g, kg, t -- "plate-a, 3, stone"
shortest row 1 rejected: 2 fields, expected 3 -- "bolt-m6, 500"
Three layers, three vocabularies, and each one is ignorant of the layer above by design. unit_grams knows the letters g, kg and t and has never heard of a record. parse_record knows about fields and returns a RecordError that mentions no row number, because it cannot know one -- the same function would work on a single line typed at a prompt. import is the first layer that knows the row number and the raw text, so it is the layer that attaches them. And main is the only function in the program that decides anything: everything below it either succeeds or hands the problem up.
The recovery arm is the part worth studying. Err(RecordError::Comment) => continue sits between the success arm and the propagating arm, so import handles exactly one error kind by name and forwards every other kind without listing them. Recover from the specific, propagate the general -- that shape is most of what real error handling looks like, and it only works because the leaf returns a typed error. Had parse_record returned String, import would be inspecting message text to decide whether to skip a line, and adding a new error message would silently change which lines get skipped.
Count the return Err sites and the ceremony is easier to see than to describe. There are five. Three of them construct a new variant, and one wraps a RecordError into an ImportError with two extra fields; all four earn their space. Exactly one -- Err(e) => return Err(e) after the unit_grams call -- takes a value out of a Result and puts it straight back into an identical one. That single site is what the next lesson replaces with one character, and the reason to write it out here is so that the operator arrives as an abbreviation of something you already understand rather than as magic.
The honest limits, starting with the one I would change first. RecordError::Comment is not an error: a blank line is a perfectly successful parse of nothing, and putting it in the error enum means explain has an arm that can never run and every caller has to remember to skip it. Result<Option<Record>, RecordError> is the honest signature, and the change is one arm in import. Second, import stops at the first bad row, which is correct for a transactional load and wrong for a bulk one where the operator wants every problem in a single pass -- collecting them means returning Vec<ImportError> alongside a partial success, which is a different function with a different contract, not a tweak. Third, ImportError clones the whole offending line; that is nothing for one error and worth thinking about if you collect thousands. Fourth, quantity * per_unit is u32 multiplication, so 4295 tonnes overflows it -- in a debug build that panics, and in a release build it silently wraps, which is precisely the failure mode the panic lesson warned about. A real version uses u64 or checked_mul and turns the overflow into another RecordError variant.
Common Mistakes
- Handling an error in a function that has no context to decide with. A parser that decides to substitute a default has made a policy choice on behalf of every future caller, and none of them can override it.
- Converting to
Stringat the first hop.format!("{e}")is cheap and irreversible. Two layers up, nobody can ask whether the number was empty or too large, and the only remaining option is matching on the text.
Box<dyn Error>in a library's public signature. Your callers can print it and nothing else. Inside a binary it is a reasonable convenience; on an API boundary it is a refusal to describe your own failure modes.
- A
Fromimpl that fakes the context it cannot see.Fromgets the error and only the error. An impl that fills inkey: "unknown"makes every error claim to carry a key, which is worse than a variant that admits it has none.
- Logging and propagating. If every layer logs on the way up, one failure produces four log lines that look like four failures. Log where you decide, once.
- Wrapping without keeping the cause.
ImportError { row, text }with theRecordErrordropped tells you which line failed and refuses to say why.
- Letting a leaf error type reach the top unchanged. If your top-level type is
ParseIntError, your public signature is now tied to a decision made five layers down, and swappingparsefor anything else is a breaking change.
- A bare
_ => continuein a recovery loop. That recovers from every error, including the ones invented after you wrote the loop. Name the variants you mean.
- Returning
Ok(default)instead of propagating. The signature still says the function can fail, the caller's error arm never runs, and the wrong value travels on looking exactly like a right one.
Best Practices
- Detect low, decide high. The function that notices the problem should describe it; the function with enough context should choose what happens.
- Give each layer its own error type, and make each type mention only what that layer can actually know about.
- Store the cause as a field rather than a rendered message, so the layer that formats the output is the layer that knows the audience.
- Add exactly what your layer knows when you wrap -- a row number, a key name, a file path -- and nothing you had to guess at.
- Reach for a named enum in libraries and
Box<dyn Error>in binaries. The question to ask is whether a caller might want to match on the failure.
- Write
Fromimpls only for conversions that need no context, and convert by hand wherever a field name, index or path has to come along.
- Recover from named variants and propagate the rest. A catch-all in a recovery position quietly widens every time somebody adds a variant.
- Let
mainreturnResult. It is the one place where propagating instead of handling costs you nothing and gets you a non-zero exit status for free.
Practice Exercises
- Add a
MaxQuantityrule to the stock importer: any quantity above 10000 is rejected. Decide whether the check belongs inparse_recordor inimport, implement it there, and write two sentences justifying the choice in terms of which layer knows the limit.
- Change
RecordError::Commentinto the honest signatureResult<Option<Record>, RecordError>. List every line of the program that has to change, then say which of them you consider an improvement and which is pure churn.
- Give
AppErrora third variantEmpty, returned when the text is blank, and add aFrom<ParseIntError>test case proving that an empty string reachesAppError::Emptyand notAppError::Parse--parsereturns an error for both, so the order of your checks decides the answer.
- Take the
ratiofunction and replaceBox<dyn Error>with a two-variant enum, addingFromimpls for bothParseIntErrorandParseFloatError. Then write down whatmaincan do afterwards that it could not do before.