Error handling
15 steps in 5 sets of Rust.
Rust has no exceptions, so error handling is in the type system and you cannot ignore it by accident. Option first, then Result and the ? operator that makes it bearable.
Then writing your own error types, which is where most real projects end up, and finally panics: when to use them, how to catch them, and why unwrap in library code will eventually embarrass you.
Option
- OptionRepresenting a value that may be absent.
- Option combinatorsWorking inside an Option instead of unwrapping it at every step.
- Between Option and ResultThe two conversions worth memorising: ok_or adds an error, ok drops one.
Result & the ? operator
- Result and ?Recoverable errors, and the ? early-return operator.
- The ? operator? returns the error early, so the happy path reads as a straight line.
- Reshaping errorsmap_err rewrites the error while leaving a successful value alone.
- Returning Result from mainmain can return a Result, and the runtime reports the error for you.
Your own error types
- A custom error enumOne enum per failure mode, with a Display impl that reads like a sentence.
- Implementing std::error::ErrorThe Error trait is what lets your type travel as a boxed error and report a cause.
- From conversions drive ?Implement From for each underlying error and ? converts on its own.
- Box<dyn Error>A boxed trait object holds any error, which suits application code and mains.
- TryFrom for checked conversionsTryFrom is From for conversions that may fail, and it gives you try_into.
Panics & recovery
- Panic or ResultPanics are for bugs; Results are for conditions your caller can handle.
- Reacting per error kindMatching on an error's variant so each failure gets its own recovery.
Encore
- config_check.rsA validation pipeline: parse key-value text, collect every problem, report.