liveBook · Manning

Error type

As explained in Refactoring to Rust

A custom error type is a programmer-defined type that represents the distinct failure conditions an operation can return.

A custom error type names the failures an operation can return. In Rust, an enum works well when an operation has several possible failures: each variant gives callers a case they can handle separately. The conventional name `Error` is not special; it is an ordinary programmer-defined type. section 2.5.4

Start with one failure

A FizzBuzz function that rejects negative input can define `enum Error { GotNegative }` and return `Result<FizzBuzzValue, Error>`. It returns `Err(Error::GotNegative)` for negative input. Its caller can match that variant to print a specific message, rather than treating every failure alike. section 2.5.4

Use `?` when a function should pass an error to its caller without inspecting it. For example, `let result = fizzbuzz(i)?;` replaces a match that extracts `Ok` or returns `Err`. This forwarding is an explicit choice in a function that returns a compatible `Result`. section 2.5.4 section 2.6

Grow the enum as failures appear

An arithmetic evaluator begins with an empty `Error` enum, then adds `InvalidNumber` when parsing can fail. A stack operation adds `PopFromEmptyStack` and returns `Result<i32, Error>`; the evaluator uses `stack.pop()?` to pass that failure onward. Its C-facing `solve` function keeps the Rust `Result` inside the library and converts success or failure to an integer return code. section 3.2.3

A public function cannot expose a private error type in its return value. When `evaluate` becomes `pub fn evaluate(problem: &str) -> Result<i32, Error>`, its `Error` enum must also become public so callers can identify the failure. If an error must be printed with `{}`, implementing `Display` for the type is considered best practice. section 4.5 section 3.3

How Refactoring to Rust covers it

How deep it goes
Works from a single enum variant through calculator parsing and stack failures to propagation and public API visibility; defers error formatting implementation.
Examples
Uses negative FizzBuzz input, invalid calculator numbers, an empty stack, and a compiler error for a private return type.
What it assumes
Introduces the error enum through a one-failure example, then builds on `Result` and matching before applying errors in a calculator.
What you can do after
Build it from scratch: define error variants, return them in `Result`, propagate them with `?`, and expose the type when required.
How it connects
Connects enum variants with `Result`, pattern matching, the `?` operator, FFI return codes, and `Display`.

Also explained in

Compare how 5 books explain error type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.