Errors as values
Replace Option and expect with Result, the ? operator and two small error enums, and decide which failures are skipped and which end the run.
- lesson
- 04 of 08
- read
- 16 min
Rust has no exceptions. A function that can fail returns Result<T, E>, an enum with the variants Ok(T) and Err(E), and the caller decides what to do with a failure. This lesson converts tally to that model. The parser reports what is wrong with a line, and a missing file produces a message instead of a panic. The program also gets a rule for which failures it skips and which end the run.
An error type for the parser
parse_line returns None for every kind of bad line. To give a reason it needs an error type, and an enum fits, because variants can carry data:
#[derive(Debug)]
pub enum ParseError {
Missing(&'static str),
BadStatus(String),
BadSize(String),
}Missing holds the name of the absent field. Its type, &'static str, is a string slice that stays valid for the whole run of the program, which is true of every string literal. The other two variants hold the text that could not be parsed.
An error type is expected to implement two traits from the standard library. Display produces the message for a person to read. Error marks the type as an error, so that generic error-handling code accepts it.
use std::error::Error;
use std::fmt;
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::Missing(field) => write!(f, "missing {field}"),
ParseError::BadStatus(text) => write!(f, "invalid status {text:?}"),
ParseError::BadSize(text) => write!(f, "invalid size {text:?}"),
}
}
}
impl Error for ParseError {}Display is the trait behind {} in format strings. match self takes the enum apart and binds the data inside each variant to a name. {text:?} formats the string with Debug, which adds quotes around it. The Error impl is empty because all of its methods have defaults; it only requires that Debug and Display exist.
The question mark operator
pub fn parse_line(line: &str) -> Result<Entry, ParseError> {
let (addr, rest) = line.split_once(' ').ok_or(ParseError::Missing("request"))?;
// The request is the first double-quoted field.
let (_, rest) = rest.split_once('"').ok_or(ParseError::Missing("request"))?;
let (request, rest) = rest.split_once('"').ok_or(ParseError::Missing("request"))?;
// "GET /index.html HTTP/1.1": the path is the second word.
let mut words = request.split_whitespace();
words.next().ok_or(ParseError::Missing("method"))?;
let path = words.next().ok_or(ParseError::Missing("path"))?;
// After the request: status, then size ("-" when no body was sent).
let mut fields = rest.split_whitespace();
let status = fields.next().ok_or(ParseError::Missing("status"))?;
let status = match status.parse::<u16>() {
Ok(code) => code,
Err(_) => return Err(ParseError::BadStatus(status.to_string())),
};
let bytes = match fields.next().ok_or(ParseError::Missing("size"))? {
"-" => None,
text => {
let n = text
.parse::<u64>()
.map_err(|_| ParseError::BadSize(text.to_string()))?;
Some(n)
}
};
Ok(Entry {
addr: addr.to_string(),
path: path.to_string(),
status,
bytes,
})
}ok_or turns an Option into a Result: Some(v) becomes Ok(v), and None becomes Err with the error given. The ? that follows does the work of each let ... else { return None; } in lesson 3. If the value is Ok, ? unwraps it. If it is Err, ? returns that error from the enclosing function. Every point of failure stays visible as one character, and control can leave the function only at a ? or a return.
The status code is written out as a match to show what ? stands for. The size uses the usual short form: map_err replaces the error inside a Result, here the standard library’s ParseIntError, with one of tally’s own. Its argument, |_| ..., is a closure: an inline function, in this case one that ignores its parameter. Lesson 5 covers closures.
Skip or stop
main now meets two kinds of failure, and they should not be treated alike.
If a file cannot be read, there is no correct summary of the input. The program has to stop and say so. A malformed line in a file of thousands is different: the summary of the other lines still means something, and one damaged line is no reason to discard it. Skipping silently would be wrong too, because the totals would then describe less data than the reader assumes. So tally skips the line and says so, with a warning and a count. In main, the let ... else from lesson 3 becomes a match on the result, and the loop over lines now starts like this:
for (index, line) in contents.lines().enumerate() {
let entry = match parse_line(line) {
Ok(entry) => entry,
Err(err) => {
eprintln!("{path}:{}: {err}", index + 1);
skipped += 1;
continue;
}
};enumerate pairs each line with its index, starting at zero. eprintln! writes to standard error, which keeps diagnostics out of the report on standard output: with 2>/dev/null appended, the command prints the summary alone.
The question to ask of any failure is whether the caller can still produce a result that is correct and says what it left out. If so, record the problem and continue. If not, return the error. Lesson 7 adds a --strict flag for the occasions when one bad line should be fatal.
Propagating I/O errors
To use ? on fs::read_to_string, the surrounding function has to return a Result. main is allowed to. It needs an error type of its own, which goes in a new file:
use std::error::Error;
use std::fmt;
use std::io;
#[derive(Debug)]
pub enum TallyError {
NoInput,
Io(io::Error),
}
impl fmt::Display for TallyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TallyError::NoInput => write!(f, "no input files"),
TallyError::Io(err) => write!(f, "{err}"),
}
}
}
impl Error for TallyError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TallyError::NoInput => None,
TallyError::Io(err) => Some(err),
}
}
}source is the one method of Error worth overriding: it exposes the underlying error to code that wants to print or inspect the chain of causes. In main.rs, declare the module with mod error;, import the type with use error::TallyError;, and change the start of main:
fn main() -> Result<(), TallyError> {
let paths: Vec<String> = env::args().skip(1).collect();
if paths.is_empty() {
return Err(TallyError::NoInput);
}
let mut requests = 0;
let mut skipped = 0;
let mut bytes = 0;
for path in &paths {
let contents = fs::read_to_string(path)?;The rest of the loop is unchanged, and the function now ends with Ok(()). The value () is the unit type, what a function returns when it has nothing to return. collect gathers the arguments into a Vec<String> so that they can be counted before use.
error[E0277]: `?` couldn't convert the error to `TallyError`
--> src/main.rs:21:48
|
10 | fn main() -> Result<(), TallyError> {
| ---------------------- expected `TallyError` because of this
...
21 | let contents = fs::read_to_string(path)?;
| ------------------------^ the trait `From<std::io::Error>` is not implemented for `TallyError`
| |
| this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
|
note: `TallyError` needs to implement `From<std::io::Error>`
--> src/error.rs:6:1
|
6 | pub enum TallyError {
| ^^^^^^^^^^^^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
For more information about this error, try `rustc --explain E0277`.read_to_string fails with an io::Error, and main returns a TallyError. The last note says what ? does about the mismatch: it converts the error with the From trait. In other words, ? on an Err(e) executes return Err(From::from(e)). Supplying the conversion fixes the build:
impl From<io::Error> for TallyError {
fn from(err: io::Error) -> Self {
TallyError::Io(err)
}
}From converts one value into another and has nothing else to work with. It cannot know which file was being read, so the message will not name the file. Lesson 7 fixes that when the input code is rewritten.
cargo run -q -- nope.logError: Io(Os { code: 2, kind: NotFound, message: "No such file or directory" })When main returns an Err, the runtime prints it with Debug and exits with status 1. That format is meant for programmers. To print the Display text, rename the function to run and call it from a main that handles the result:
mod entry;
mod error;
use std::env;
use std::fs;
use std::process;
use entry::{StatusClass, parse_line};
use error::TallyError;
fn run() -> Result<(), TallyError> {
let paths: Vec<String> = env::args().skip(1).collect();
if paths.is_empty() {
return Err(TallyError::NoInput);
}
let mut requests = 0;
let mut skipped = 0;
let mut bytes = 0;
for path in &paths {
let contents = fs::read_to_string(path)?;
for (index, line) in contents.lines().enumerate() {
let entry = match parse_line(line) {
Ok(entry) => entry,
Err(err) => {
eprintln!("{path}:{}: {err}", index + 1);
skipped += 1;
continue;
}
};
requests += 1;
if let Some(n) = entry.bytes {
bytes += n;
}
match entry.class() {
StatusClass::ClientError | StatusClass::ServerError => {
println!("{} {} from {}", entry.status, entry.path, entry.addr);
}
_ => {}
}
}
}
println!("{requests} requests, {skipped} lines skipped, {bytes} bytes");
Ok(())
}
fn main() {
if let Err(err) = run() {
eprintln!("tally: {err}");
process::exit(1);
}
}cargo run -q -- access.log404 /favicon.ico from 203.0.113.7
access.log:8: missing request
500 /api/orders from 192.0.2.44
403 /admin from 192.0.2.44
access.log:15: missing path
404 /favicon.ico from 2001:db8::1f
502 /api/orders from 198.51.100.23
16 requests, 2 lines skipped, 152631 bytescargo run -q -- nope.logtally: No such file or directory (os error 2)What thiserror and anyhow would change
The Display, Error and From impls for TallyError are boilerplate, and two widely used crates exist to remove it. thiserror generates the impls from attributes. With version 2.0.21, all of error.rs shrinks to this:
use std::io;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum TallyError {
#[error("no input files")]
NoInput,
#[error(transparent)]
Io(#[from] io::Error),
}anyhow (version 1.0.105) goes the other way and removes the enum. Its anyhow::Result<T> accepts any error type through ?, and a call such as .with_context(|| format!("reading {path}")) attaches a message on the way up.
The two suit different code. A typed enum, written by hand or with thiserror, is for errors that a caller will inspect and branch on, the normal situation in a library. anyhow is for application code that only reports errors to a person. tally keeps its hand-written enums. They cost under fifty lines and no dependency, and lesson 7 needs to match on one of the variants.
Exercises
- Make an empty line a case of its own. Add a variant
EmptytoParseError, return it fromparse_linewhenline.trim().is_empty(), and give it the messageempty line. Create a test file withcp access.log copy.log; echo >> copy.log. The last warning for it should readcopy.log:19: empty line. - Skipping should have a limit. Add a variant to
TallyErrorthatrunreturns once more than 10 lines of a single file have been skipped, with a message such assrc/entry.rs: more than 10 malformed lines, and try it by runningtallyon one of its own source files. - Run
cargo add thiserror, replace the hand-written impls inerror.rswith the derive shown above, and check that both failure messages are unchanged:tally: no input filesand the one for a missing file. Then restore the hand-written file and runcargo remove thiserror, since later lessons build on that version.