Think about how errors work in a JavaScript backend. Any function can throw. Nothing in its signature tells you whether it might, or what it might throw. You find out by reading the source, reading the docs if they exist, or hitting it in production. JSON.parse throws. fetch rejects on network failure but not on a 500. A missing property gives you undefined, which throws three functions later when something calls a method on it.
Rust doesn't have exceptions. It doesn't have null either. Instead, a function that might not have a value returns Option<T>, and a function that might fail returns Result<T, E>. Both are ordinary enums of the kind we wrote in part 4, and both appear in the function's signature, so you can see at a glance what can go wrong. The compiler won't let you use the value inside until you've dealt with the other case.
That sounds like it would make code verbose, and it would, if not for the ? operator. In this part we'll go from basic Option and Result handling, through ?, to custom error types, the two crates nearly every Rust project uses for errors (thiserror and anyhow), and when it's right to give up and panic. Then we'll take every process::exit out of the middle of wordfreq.
All outputs come from real runs on Rust 1.100.0, with thiserror 2.0.21 and anyhow 1.0.105.
Two kinds of failure
Rust splits problems into two groups, and it's worth being clear about which is which before we start.
Recoverable errors are things that can reasonably happen in a correct program: a file isn't there, a user typed letters into a number field, the database is down, a JSON body is malformed. The code should expect them and decide what to do. These are Result values.
Unrecoverable errors are bugs: an index past the end of an array, a value that your own logic guarantees can't be None turning out to be None, integer overflow in debug builds. Continuing would mean running in a state your code doesn't understand. These are panics, which stop the current thread.
JavaScript uses one mechanism, exceptions, for both, which is part of why try/catch blocks so often catch things they weren't meant to. Rust keeps them apart.
Option: maybe a value
Option<T> is either Some(value) or None. Here's a lookup that might not find anything:
fn find_user(id: u64) -> Option<&'static str> {
match id {
1 => Some("ana"),
2 => Some("bo"),
_ => None,
}
}
user 1: Some("ana")
user 9: None
The point is what you can't do with it. You can't treat an Option<u32> as a u32:
let age: u32 = find_age("ana");
error[E0308]: mismatched types
--> src/bin/e_optval.rs:6:20
|
6 | let age: u32 = find_age("ana");
| --- ^^^^^^^^^^^^^^^ expected `u32`, found `Option<u32>`
| |
| expected due to this
|
= note: expected type `u32`
found enum `Option<u32>`
help: consider using `Option::expect` to unwrap the `Option<u32>` value, panicking if the value is an `Option::None`
In TypeScript with strictNullChecks, number | undefined gives you a similar check. The difference is that Rust has no way to opt out and no any to slip through. Every possible absence is visible in the types.
Getting the value out
You can always match:
let display = match find_user(2) {
Some(name) => format!("hello, {name}"),
None => "hello, stranger".to_string(),
};
hello, bo
But most of the time a method says it more clearly. These are the ones you'll use daily, with real output:
println!("unwrap_or: {}", find_user(9).unwrap_or("guest"));
println!("map: {:?}", find_user(1).map(|n| n.len()));
println!("map on None: {:?}", find_user(9).map(|n| n.len()));
println!("is_some: {}, is_none: {}", find_user(1).is_some(), find_user(9).is_none());
println!("and_then: {:?}", find_user(2).and_then(|n| n.chars().nth(1)));
println!("ok_or: {:?}", find_user(9).ok_or("no such user"));
unwrap_or: guest
map: Some(3)
map on None: None
is_some: true, is_none: true
and_then: Some('o')
ok_or: Err("no such user")
| Method | What it does | JavaScript equivalent |
|---|---|---|
unwrap_or(default) |
Value or a default | x ?? default |
unwrap_or_else(|| ...) |
Value or a computed default | x ?? compute() |
unwrap_or_default() |
Value or the type's default (0, "", empty) | x ?? 0 |
map(f) |
Transform the value if there is one | x?.foo or x && f(x) |
and_then(f) |
Chain another step that might return None |
x?.foo?.bar |
is_some(), is_none() |
Check without taking the value | x !== undefined |
ok_or(err) |
Turn None into an error |
if (!x) throw err |
if let Some(x) = ... |
Do something only when present | if (x) { ... } |
map and and_then are what make Option pleasant. map applies a function to the inside value and leaves None alone, so you can transform an optional value without unpacking it. and_then is for when the function itself returns an Option, so you get Option<T> instead of Option<Option<T>>.
A hash map lookup is the most common source of Option in web code:
let theme = prefs.get("theme").copied().unwrap_or("light");
let lang = prefs.get("lang").copied().unwrap_or("en");
theme=dark lang=en
(.get() returns Option<&V>, a reference into the map. .copied() turns it into an Option<V> for Copy types like &str, so the default and the found value have the same type.)
Result: success or an error
Result<T, E> is either Ok(value) or Err(error). Parsing a number returns one:
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse::<u16>()
}
for input in ["8080", " 3000 ", "http", "70000", ""] {
match parse_port(input) {
Ok(port) => println!("{input:?} -> port {port}"),
Err(e) => println!("{input:?} -> error: {e}"),
}
}
"8080" -> port 8080
" 3000 " -> port 3000
"http" -> error: invalid digit found in string
"70000" -> error: number too large to fit in target type
"" -> error: cannot parse integer from empty string
The signature tells you everything: give it a string, get either a u16 or a ParseIntError. Notice "70000" failing. A u16 can't hold it, and the parser says so instead of wrapping or truncating. That's the try_from behaviour I promised in part 2.
Errors usually have two text forms. {e} uses Display, written for humans: "invalid digit found in string". {e:?} uses Debug, written for developers:
debug form: Err(ParseIntError { kind: InvalidDigit })
Log the Debug form, show users the Display form.
Result has the same family of methods as Option:
let port = parse_port("oops").unwrap_or(3000);
let doubled = parse_port("21").map(|p| p * 2);
let msg = parse_port("x").map_err(|e| format!("bad PORT setting: {e}"));
println!("ok(): {:?} {:?}", parse_port("1").ok(), parse_port("x").ok());
unwrap_or default: 3000
map: Ok(42)
map_err: Err("bad PORT setting: invalid digit found in string")
ok(): Some(1) None
map_err transforms the error and leaves a success alone. You'll use it constantly to turn a low-level error into one that makes sense for your code. .ok() converts a Result to an Option, throwing the error away, which is handy when you genuinely don't care why something failed.
You can't ignore a Result
What if you call something that returns a Result and just don't look at it?
fs::write("/tmp/out.txt", "hello");
warning: unused `Result` that must be used
--> src/bin/e_unused.rs:4:5
|
4 | fs::write("/tmp/out.txt", "hello");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
It's a warning rather than an error, but it's one you should treat as an error. The JavaScript equivalent is calling an async function without await and never finding out it failed, a bug that has quietly lost data in plenty of Node apps. If you really mean to ignore it, let _ = ... makes that a visible decision.
The ? operator
Here's the pattern you'd write over and over without help. Parse two ports, and return the first error if either fails:
fn parse_pair_long(a: &str, b: &str) -> Result<(u16, u16), ParseIntError> {
let x = match parse_port(a) {
Ok(v) => v,
Err(e) => return Err(e),
};
let y = match parse_port(b) {
Ok(v) => v,
Err(e) => return Err(e),
};
Ok((x, y))
}
And here's the same function with ?:
fn parse_pair(a: &str, b: &str) -> Result<(u16, u16), ParseIntError> {
let x = parse_port(a)?;
let y = parse_port(b)?;
Ok((x, y))
}
pair: Ok((80, 443))
pair: Err(ParseIntError { kind: InvalidDigit })
long form agrees: true
? after a Result means: if it's Ok, give me the value and carry on; if it's Err, return that error from this function right now. It's exactly the match above, in one character.
This is the closest thing Rust has to exceptions, and it's worth comparing directly. In JavaScript, an error thrown deep in a call stack travels up invisibly until something catches it. In Rust, an error travels up the stack one ? at a time, and every function it passes through says so in its return type. You get the brevity of exceptions without the invisibility. When you read let user = load_user(id)?; you know two things: this might fail, and if it does, this function fails too.
? works on Option as well, returning None early:
fn first_letter_upper(id: u64) -> Option<char> {
let name = find_user(id)?;
let first = name.chars().next()?;
Some(first.to_ascii_uppercase())
}
? on Option: Some('A') None
That reads like JavaScript's optional chaining, findUser(id)?.[0]?.toUpperCase(), and does the same job.
Where ? is allowed
? returns early, so it only works inside a function whose return type can hold the error. Use it in a plain main and you get this:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/bin/e_qmain.rs:4:47
|
3 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
4 | let text = fs::read_to_string("notes.txt")?;
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
3 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
4 | let text = fs::read_to_string("notes.txt")?;
5 | println!("{text}");
6 + Ok(())
|
The compiler's suggestion works. main can return a Result:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let text = fs::read_to_string("/tmp/does-not-exist.txt")?;
println!("{text}");
Ok(())
}
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
The process exits with status 1 and prints the error's Debug form. That's fine for a quick script, but notice it isn't a friendly message. We'll do better for wordfreq.
Collecting results
One more trick that comes up all the time in web code, such as validating every item in a request body. If you have a list of things that might each fail, collect can gather them into a Result of a list:
let results: Result<Vec<u16>, _> = ["1", "2", "3"].iter().map(|s| parse_port(s)).collect();
let results: Result<Vec<u16>, _> = ["1", "nope", "3"].iter().map(|s| parse_port(s)).collect();
collect all ok: Ok([1, 2, 3])
collect with one bad: Err(ParseIntError { kind: InvalidDigit })
All succeed and you get Ok with every value, or the first failure stops it and you get that Err. It's Promise.all semantics for ordinary values.
Custom error types
Real functions can fail in more than one way. Loading a config might fail because a setting is missing, isn't a number, or is out of range. A caller might want to handle those differently, and a user definitely wants to know which one happened. An enum is the natural fit:
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
BadNumber { key: &'static str, source: ParseIntError },
OutOfRange { key: &'static str, value: u32, max: u32 },
}
Each variant carries the details for its case. BadNumber holds the original ParseIntError as its source, so the low-level cause isn't lost.
To print it nicely, implement Display. This is our first hand-written trait implementation (traits get their own part, part 7), but you can read it as "here's how to format this type":
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "{key} is not set"),
ConfigError::BadNumber { key, source } => write!(f, "{key} is not a number ({source})"),
ConfigError::OutOfRange { key, value, max } => {
write!(f, "{key} is {value}, the maximum is {max}")
}
}
}
}
impl std::error::Error for ConfigError {}
The last line marks it as a standard error type, which lets it work with the generic error tools we'll see shortly. Now the function that uses it:
fn read_number(env: &[(&str, &str)], key: &'static str, max: u32) -> Result<u32, ConfigError> {
let raw = env
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| *v)
.ok_or(ConfigError::Missing(key))?;
let value: u32 = raw
.parse()
.map_err(|source| ConfigError::BadNumber { key, source })?;
if value > max {
return Err(ConfigError::OutOfRange { key, value, max });
}
Ok(value)
}
fn load(env: &[(&str, &str)]) -> Result<Config, ConfigError> {
Ok(Config {
port: read_number(env, "PORT", 65535)?,
workers: read_number(env, "WORKERS", 64)?,
})
}
Three error paths, three techniques. ok_or turns a missing value into Missing. map_err wraps the parse error into BadNumber. A plain return Err(...) handles the range check. And load uses ? inside a struct literal, which works fine.
Four environments, four outcomes:
ok: Config { port: 8080, workers: 4 }
error: WORKERS is not set
debug: Missing("WORKERS")
error: PORT is not a number (invalid digit found in string)
debug: BadNumber { key: "PORT", source: ParseIntError { kind: InvalidDigit } }
error: WORKERS is 500, the maximum is 64
debug: OutOfRange { key: "WORKERS", value: 500, max: 64 }
A caller can match on the variant to react differently, say retrying on one kind of error and failing fast on another, and the user gets a sentence that tells them what to fix. Compare that to a JavaScript function that throws new Error("bad config") and leaves the caller to parse the message string.
Making ? convert errors with From
What if one function calls two things with different error types? Reading a number from a file can fail with an io::Error (no file) or a ParseIntError (not a number). If the function returns Result<_, ParseIntError>, ? on the file read won't compile:
error[E0277]: `?` couldn't convert the error to `ParseIntError`
--> src/bin/e_qmismatch.rs:4:45
|
3 | fn read_port(path: &str) -> Result<u16, ParseIntError> {
| -------------------------- expected `ParseIntError` because of this
4 | let text = std::fs::read_to_string(path)?;
| -----------------------------^ the trait `From<std::io::Error>` is not implemented for `ParseIntError`
| |
| this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
The note is the key: "the question mark operation (?) implicitly performs a conversion on the error value using the From trait". ? doesn't just return the error, it converts it into the function's error type first, if it knows how. So we define an error type that can hold either, and tell Rust how to convert into it:
#[derive(Debug)]
enum AppError {
Io(io::Error),
Parse(ParseIntError),
}
impl From<io::Error> for AppError {
fn from(e: io::Error) -> Self {
AppError::Io(e)
}
}
impl From<ParseIntError> for AppError {
fn from(e: ParseIntError) -> Self {
AppError::Parse(e)
}
}
fn read_count(path: &str) -> Result<i64, AppError> {
let text = fs::read_to_string(path)?;
let n = text.trim().parse::<i64>()?;
Ok(n)
}
With a Display implementation like before, three files give three results:
/tmp/good.txt: 42
/tmp/bad.txt: the file does not hold a number: invalid digit found in string
/tmp/missing.txt: could not read the file: No such file or directory (os error 2)
read_count is as short as it would be in a language with exceptions, and the error type still tells callers exactly what can go wrong.
Boxed errors, for when you don't care which
Sometimes you don't need callers to distinguish error kinds. You just want "something went wrong, here's the message". Box<dyn std::error::Error> is a type that can hold any error:
fn sum_files(paths: &[&str]) -> Result<i64, Box<dyn std::error::Error>> {
let mut total = 0;
for p in paths {
total += fs::read_to_string(p)?.trim().parse::<i64>()?;
}
Ok(total)
}
boxed sum: 84
boxed error: No such file or directory (os error 2)
No From impls needed, because every standard error converts into a Box<dyn Error> automatically. The cost is that callers can no longer match on the kind of error without extra work. (dyn means "some type implementing this trait, decided at runtime", which part 7 explains.)
thiserror and anyhow
Writing Display and From by hand for every error type gets repetitive. Almost every Rust project uses one or both of two crates by David Tolnay to remove the boilerplate:
cargo add thiserror anyhow
thiserror: custom error types without the boilerplate
use thiserror::Error;
#[derive(Debug, Error)]
enum SignupError {
#[error("email {0:?} is missing an @")]
BadEmail(String),
#[error("password must be at least {min} characters, got {got}")]
ShortPassword { min: usize, got: usize },
#[error("could not save the user")]
Storage(#[from] std::io::Error),
}
#[derive(Error)] generates the std::error::Error implementation. Each #[error("...")] attribute generates that variant's Display text, with fields filled in by name or position. #[from] generates the From impl, so ? on an io::Error converts into SignupError::Storage automatically.
fn signup(email: &str, password: &str) -> Result<(), SignupError> {
if !email.contains('@') {
return Err(SignupError::BadEmail(email.to_string()));
}
if password.len() < 12 {
return Err(SignupError::ShortPassword { min: 12, got: password.len() });
}
fs::write("/nonexistent-dir/users.txt", email)?;
Ok(())
}
signup error: email "ana.example.com" is missing an @
signup error: password must be at least 12 characters, got 5
signup error: could not save the user
The generated code is exactly what you'd have written by hand. thiserror doesn't appear in your public API at all, it only writes the impls for you.
anyhow: one error type for application code
anyhow::Result<T> is a Result whose error can be anything, like Box<dyn Error>, with two extras that matter a lot in practice: adding context, and a quick way to fail with a message.
use anyhow::{Context, bail};
fn load_settings(path: &str) -> anyhow::Result<u16> {
let text = fs::read_to_string(path).with_context(|| format!("reading settings from {path}"))?;
let port: u16 = text.trim().parse().context("PORT in settings is not a number")?;
if port < 1024 {
bail!("port {port} needs root, pick one above 1023");
}
Ok(port)
}
Printed with {:#}, which shows the context and its cause on one line:
/tmp/s1.txt: port 8080
/tmp/s2.txt: PORT in settings is not a number: invalid digit found in string
/tmp/s3.txt: port 80 needs root, pick one above 1023
/tmp/nope.txt: reading settings from /tmp/nope.txt: No such file or directory (os error 2)
Look at the last line. The raw io::Error only says "No such file or directory". It doesn't say which file. .with_context(...) adds the part that makes the error useful: what we were trying to do. This is the single biggest improvement you can make to error messages in any language, and anyhow makes it one method call. bail! returns early with an error built from a format string.
Which one to use
The common rule of thumb in the Rust community:
- Use thiserror for libraries and for any code where callers need to tell errors apart, such as deciding which HTTP status to return.
- Use anyhow for application code where errors mostly get reported, not handled: command line tools, startup code, scripts.
Many projects use both: thiserror for the error types of their domain logic, and anyhow at the top level in main. When we build the Axum app, we'll use a thiserror enum for errors that map to HTTP responses, because a "not found" and a "database is down" need different status codes, and anyhow would hide that difference.
Panics
Sometimes there's no sensible way to continue. That's what panic! is for. It prints a message and unwinds the current thread. You've seen panics from overflow and from slicing a string in the middle of a character. Here are the three you'll meet most.
.unwrap() on an Err:
thread 'main' (849) panicked at src/bin/panics.rs:5:44:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
.expect("..."), which is unwrap with your own message:
let port: u16 = "http"
.parse()
.expect("PORT should be a number between 0 and 65535");
thread 'main' (912) panicked at src/bin/panics.rs:11:18:
PORT should be a number between 0 and 65535: ParseIntError { kind: InvalidDigit }
And indexing out of bounds:
thread 'main' (923) panicked at src/bin/panics.rs:17:33:
index out of bounds: the len is 3 but the index is 5
All three exit with status 101. Setting RUST_BACKTRACE=1 adds a stack trace.
When panicking is the right call
unwrap gets a bad reputation, and in request-handling code it deserves it. But it's not always wrong. Reasonable uses:
- Tests. A failing
unwrapin a test is a test failure with a clear message, which is what you want. - Prototypes and examples, where error handling would hide the point.
- Startup configuration. If
DATABASE_URLis missing, the server can't do anything useful, and crashing immediately with.expect("DATABASE_URL must be set")is clearer than limping on. - Cases where your own logic guarantees success, and the compiler just can't see it. Use
expectwith a message saying why it can't fail, so the next reader knows your reasoning.
Never panic on anything that comes from a user, the network or a file at request time. In a web server, bad input should become a 400 response, not a crash. (In an Axum server, a panic in a handler ends the task serving that connection rather than the whole process, but that is a safety net, not error handling.)
I'd also suggest preferring expect over unwrap everywhere you keep one. "PORT should be a number between 0 and 65535" tells whoever reads the crash log what assumption broke. "called Result::unwrap() on an Err value" tells them almost nothing.
How this compares to JavaScript
| JavaScript | Rust |
|---|---|
null, undefined |
Option::None |
x ?? fallback |
x.unwrap_or(fallback) |
x?.y?.z |
x?.y?.z inside a function returning Option, or and_then chains |
throw new Error("...") |
return Err(...) or bail!("...") |
| Function might throw (invisible) | Return type is Result<T, E> (visible) |
try { a(); b(); } catch (e) {} |
a()?; b()?; in a function returning Result |
catch (e) { if (e instanceof NotFound) } |
match err { AppError::NotFound => ... } |
class NotFound extends Error |
Enum variant with #[error("...")] |
new Error("x", { cause }) |
#[source] field or .context("x") |
| Unhandled promise rejection | unused Result that must be used warning |
Promise.all on validations |
collect::<Result<Vec<_>, _>>() |
| Uncaught exception crashes Node | Panic, for bugs only |
Back to wordfreq
Our main function has process::exit(1) in three places, and each error path is a hand-written match with an eprintln!. Let's restructure it the way most Rust command line tools are written: all the real work moves into a run function that returns a Result, and main becomes the single place that prints errors and picks the exit code.
Add thiserror to the project:
cargo add thiserror
Define the error type:
use std::io;
use thiserror::Error;
#[derive(Debug, Error)]
enum WordfreqError {
#[error("{0}")]
Args(String),
#[error("could not read {path}: {source}")]
Read {
path: String,
#[source]
source: io::Error,
},
}
Args wraps the message from Config::from_args, which already returns Result<Config, String>. Read keeps both the path, which the raw io::Error doesn't know, and the original error as its #[source]. Marking it as the source means tools that print error chains, like anyhow, can show the underlying cause.
Now main and run:
fn main() {
if let Err(error) = run() {
eprintln!("error: {error}");
process::exit(1);
}
}
fn run() -> Result<(), WordfreqError> {
let args: Vec<String> = env::args().collect();
let config = Config::from_args(&args).map_err(WordfreqError::Args)?;
let text = fs::read_to_string(&config.path).map_err(|source| WordfreqError::Read {
path: config.path.clone(),
source,
})?;
let counts = count_words(&text);
if counts.is_empty() {
println!("{} has no words in it", config.path);
return Ok(());
}
// ... the statistics and the ranked list, unchanged ...
Ok(())
}
Two new things in there. .map_err(WordfreqError::Args) passes the enum variant itself as the function. A tuple variant like Args acts as a function that takes a String and returns a WordfreqError, so there's no need to write |msg| WordfreqError::Args(msg). And the empty-file case, which isn't an error, now returns Ok(()) early instead of return.
There's exactly one process::exit left, in main, and every error message gets the same error: prefix:
cargo run -q -- missing.txt
error: could not read missing.txt: No such file or directory (os error 2)
cargo run -q -- notes.txt --sort random
error: unknown sort "random", use count, alpha or length
Both exit with status 1. The empty file still prints its message and exits with 0, since an empty file is valid input. Normal runs are unchanged:
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line
sorted by Count
1. is 4 ####
2. the 4 ####
And a test for the error message:
#[test]
fn read_error_names_the_file() {
let source = io::Error::new(io::ErrorKind::NotFound, "gone");
let error = WordfreqError::Read {
path: "x.txt".to_string(),
source,
};
assert_eq!(error.to_string(), "could not read x.txt: gone");
}
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
.to_string() works on anything that implements Display, which thiserror generated for us. Testing error messages like this is worth doing for anything a user will see, because they're part of your program's interface.
The shape we've ended up with, a run function returning Result and a thin main, is the same shape our Axum app will have. Handlers will return Result<Json<T>, AppError>, and a single conversion will turn every AppError into an HTTP response. The work you do with error types now carries straight over.
Exercises
- Write
fn parse_rgb(s: &str) -> Result<(u8, u8, u8), String>that accepts"255,128,0". Usesplit,?andmap_err. What happens with"256,0,0"? - Change
Config::from_argsto return a thiserror enum with separate variants for a missing path, a bad--topvalue and an unknown option. Update the tests tomatchon variants instead of checking message text. - Rewrite
read_countwithanyhow::Resultand.context(). Compare the error output for a missing file with the hand-written version. - Find every
.unwrap()in thewordfreqtests. Should any of them beexpect? Why isunwrapacceptable there? - Write a function that validates a list of email addresses and returns all of them or the first invalid one, using
collect::<Result<Vec<_>, _>>(). Then change it to return every invalid address instead of only the first. Which approach suits a form in a web app better?
Next up: modules and crates
wordfreq is now a single 250-line file holding parsing, counting, sorting, formatting, errors and tests. That's about the limit before it gets hard to work in. In part 6 we split it up: modules and files, pub and privacy, a library crate with a thin binary on top, and how to choose and manage dependencies from crates.io. We'll also replace our hand-written argument parser with clap, the crate almost every Rust command line tool uses, and set up a Cargo workspace like the one our Axum project will use.