Week 4 - The Error Model¶
4.1 Conceptual Core¶
- Rust has two error mechanisms, not one:
Result<T, E>-recoverable errors, encoded in the type system.- Panics-unrecoverable, stack-unwinding (or aborting) bugs.
?is not exception handling. It is sugar formatchplusFrom::fromon the error variant. Internalize this; it is the difference between a clean error model and a re-implementation of Java exceptions.panic = "abort"vspanic = "unwind": chooseabortfor binaries that own their process,unwindfor libraries that may be embedded in a host that wants to catch (e.g., a Python extension).
4.2 Mechanical Detail¶
- The shape of an idiomatic library error: an enum with
#[non_exhaustive],thiserror::Errorfor derivation, andFromimpls for upstream errors. - The shape of an idiomatic application error:
anyhow::Resultat boundaries, typed errors internally. The split is deliberate: libraries owe their callers structured errors; applications owe their operators readable context. Result::map_errand? - chain ergonomics. The anti-pattern ofunwrap()outsidemain/tests/build.rs`.#[track_caller]-the attribute that makes panic locations attribute to the caller rather than the panicking function. Why every helper that may panic should carry it.
4.3 Lab-"A Library With Two Faces"¶
Build parse-units: a small crate that parses strings like "3.5 GiB" into a structured Quantity. Requirements:
- Public API returns Result<Quantity, ParseError> where ParseError is a thiserror enum with at least four variants.
- Internally, use ? to compose. No unwrap allowed except in unit tests.
- Provide a binary parse-units-cli that uses anyhow and prints rich context with .with_context(|| ...).
- Ship 100% line coverage measured by cargo-llvm-cov.
4.4 Idiomatic & Clippy Drill¶
clippy::result_large_err(errors >128 bytes hurt the happy path),clippy::map_err_ignore,clippy::question_mark,clippy::unwrap_used,clippy::expect_used. Enable the last two asdenyin libraries.
4.5 Production Hardening Slice¶
- Add a
panic = "abort"release profile and apanic = "unwind"test profile. Confirm the binary shrinks under abort. AddRUST_BACKTRACE=1to your dev shell. - Wire up
cargo auditandcargo deny checkto CI. Both must pass on green main.
Month 1 Capstone Deliverable¶
A workspace foundations/ with three crates:
1. parse-units (week 4 lab) as a publishable library.
2. parse-units-cli as the application binary.
3. layout-forensics (week 2 lab) as an internal-only tool.
CI must run: cargo fmt --check, cargo clippy -D warnings, cargo test, cargo llvm-cov, cargo deny check, cargo audit. The workspace's release profile must enable lto = "fat", codegen-units = 1, panic = "abort", strip = "symbols". Document the resulting binary size in the workspace README.