Rust · Chapter 14 of 26
Error types
By the end of this chapter you can write an error enum of your own, give it Display and std::error::Error by hand and then with thiserror, let ? convert one error into another with From, use anyhow in an application to add context and stop with a message, and say when code should return each. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Traits and data
- 4 tasks
- Rust
- In the all labs plan
The first 2 chapters of Rust are free. This one comes with the all labs plan.
Why you need this
The box reads 211 lines from S001's analyser every morning, and four of them are broken in four different ways: line 18 is empty, line 59 has no litres, line 97 says ERR for fat and SNF, line 142 is cut short. On 12 October the old box treated every surprise the same way: it crashed. The new box must do something different for each. An empty line is the analyser's update talking and can be skipped quietly; a bad number means Lakhan's team must look at the analyser; and when Neha's payout run reads a whole log and stops, she needs to know which line, and why.
Chapter 9 gave you Result<T, String>, and a String is a poor error for this. The box can only tell an empty line from a broken one by reading the words: if e.starts_with("line") && e.ends_with("is empty"), which breaks the day someone rewords a message. The ParseIntError that said exactly what was wrong is gone, flattened by map_err into text. Every function that calls another must map_err again to change one String into another. And there is no way to add "while reading line 59" without building a longer String by hand at every level. Rust's answer is an error type: an enum the caller can match on, which converts itself with ? and keeps its cause, plus two crates that write the dull parts for you.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
line_error.rs: LineError, with thiserror
LineError in line_error.rs has three variants, each with the line's number: Empty { line: usize }, Fields { line: usize, found: usize } and Kind { line: usize, kind: String }. Its Display and std::error::Error are written by hand, with a todo!. Replace both hand-written impl blocks with thiserror: derive Error next to Debug and PartialEq, and give each variant an #[error("...")] message (the Check reads the file for #[error( ).
The Check expects Empty { line: 18 } to print line 18 is empty, Empty { line: 3 } line 3 is empty, Fields { line: 142, found: 2 } line 142 has 2 fields, not 6, Fields { line: 9, found: 7 } line 9 has 7 fields, not 6, and Kind { line: 7, kind: "goat" } line 7: unknown kind "goat" (the kind in quotes, as {:?} prints text). Each must be a std::error::Error with no source.
- Task 2
parse.rs: parse one analyser line, with ? and #[from]
Write pub fn parse_line(n: usize, line: &str) -> Result<Can, ParseError> in parse.rs. An analyser line is time,farmer,kind,litres,fat,snf. In this order: a line that is empty or only spaces is LineError::Empty { line: n }; a line without exactly 6 comma-separated fields is LineError::Fields { line: n, found }; a kind other than cow or buffalo is LineError::Kind { line: n, kind }. Then the numbers, as whole numbers: take the point out of the text and parse a u32. Litres have two digits after the point, so ml is that number times 10 ("3.31" is 331, so 3310 ml); fat and SNF have one, so "8.0" is 80. Return Can { farmer, kind, ml, fat, snf }.
Make ParseError derive thiserror's Error (delete its hand-written impl blocks), with Line(#[from] LineError) marked #[error(transparent)] (it prints the LineError's message and has its source, none), and Number(#[from] ParseIntError) with the message bad number (the ParseIntError is its source, not part of its message). Use ? for both kinds of error.
The Check expects parse_line(5, "06:04:55,F10113,buffalo,3.31,8.0,9.2") to be Ok(Can { farmer: "F10113", kind: Buffalo, ml: 3310, fat: 80, snf: 92 }), and checks two more good lines (15.85 litres is 15850 ml, 4.88 is 4880). It expects Err(ParseError::Line(..)) with the LineError's own message for "" (Empty, line 18), " " (Empty, line 4), "07:55:03,F1013" (Fields, found 2), a line with 7 fields (Fields, found 7) and a goat line (Kind, "goat"). For "07:18:57,F10084,cow,9.80,ERR,ERR" (line 97) and "06:47:18,F10128,buffalo,,7.2,9.2" (line 59, no litres) it expects Err(ParseError::Number(..)) printing bad number, with the source invalid digit found in string and cannot parse integer from empty string.
- Task 3
log.rs: read the whole log, with anyhow
Write pub fn read_log(text: &str) -> anyhow::Result<Vec<Can>> in log.rs. Empty text fails with bail! and the message the analyser log is empty. Otherwise it parses every line with parse_line, numbering lines from 1, and returns all the Cans; at the first line that fails it adds the context reading analyser line N (N that line's number) to parse_line's own error and returns it with ?.
The Check expects read_log of S001's first 17 lines to be Ok with 17 cans (the second F10122's, 4880 ml). read_log(doodh::analyser_log()) must fail, printing with {:#} reading analyser line 18: line 18 is empty. read_log of S001's lines 19 to 60 must fail at its line 41 (the log's line 59, with no litres): printed with {} the error is reading analyser line 41, its chain is reading analyser line 41, bad number, cannot parse integer from empty string, and downcast_ref::<ParseError>() must find the ParseError::Number inside it. read_log("") must fail with the analyser log is empty.
- Task 4 · interview question
Interview: report.rs, the shift report that must not stop
Write pub fn shift_report(text: &str) -> ShiftReport in report.rs. It goes through every line of an analyser log with parse_line (lines numbered from 1) and never stops: a line that parses adds 1 to cans; a line that fails with ParseError::Line(LineError::Empty { .. }) adds 1 to empty; every other failure pushes the line's number to broken, in order. ShiftReport has pub fields cans: usize, empty: usize and broken: Vec<usize>.
The Check expects shift_report(doodh::analyser_log()) to be ShiftReport { cans: 207, empty: 1, broken: [59, 97, 142] }. For a short text of six lines (a can, an empty line, a goat line, an empty line, a can, a line cut short) it expects cans 2, empty 2, broken [3, 6], and for "" cans 0, empty 0 and no broken lines.
Farhan will ask: parse_line returns a thiserror enum and read_log an anyhow::Result. Which one could shift_report use to tell an empty line from a broken one, and so when does code return thiserror and when anyhow?
What you will learn
- An error enum of your own: one variant per thing that can go wrong, with its data.
- Display and std::error::Error by hand: what makes a type an error.
- From and ?: ? converts the error it returns with From.
- thiserror: #[derive(Error)], #[error("...")], #[from] and transparent.
- anyhow: anyhow::Result, .context(), .with_context() and bail!, for applications.
- Box<dyn Error>: any error at all, in one type.
- Library or application: which kind of error each should return.
More in Traits and data
Build "Error types" yourself
DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Rust are free. This one comes with the all labs plan.