Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 132 ยท Error Handling

Error Handling Design

Design good Rust error handling: libraries vs applications, typed errors instead of strings, adding context, retrying, collecting validation errors, logging.

You now know the mechanics: Result, ?, custom error types, Box<dyn Error>. The harder part of error handling is not the syntax, it is the design. Which function should decide what a failure means? How much detail should an error carry? Should you stop at the first problem or report all of them? Should the code log the error or return it? Get these decisions right and a program fails in ways that are easy to understand and fix; get them wrong and you ship messages like "invalid input" that tell nobody anything.

This lesson collects the design rules that experienced Rust programmers follow, with runnable examples for each: library versus application errors, typed versus stringly-typed errors, adding context, accumulating validation errors, retrying, reporting versus logging, and keeping panics out of reusable code. It assumes you have read Result, the ? operator and custom error types.

Rule 1: Know who is going to read the error

Every error has a reader, and the reader decides how much structure the error needs.

  • A program (the caller's code) wants to branch: retry on a timeout, create the file on "not found", show a form message on "invalid email". It needs structured errors, such as enums, that it can match on.
  • A human (a user or developer) wants a clear explanation: what was being attempted, with which input, and why it failed. It needs good messages and context.

Libraries mostly serve the first reader (and also provide good Display text), while applications mostly serve the second, because at the top of an application the error just gets shown. That difference gives the central design rule:

Library Application
Error type Your own enum or struct per module or crate Box<dyn Error> or anyhow::Error is fine
Callers need to match? Yes Rarely
Messages Concise, one layer each Full chain printed at the top
Panics Almost never Acceptable at startup for impossible setups

A common healthy architecture combines both: the libraries inside your project (modules, workspace crates) expose precise enums, and the thin main layer converts them into something printable.

Rule 2: Don't use strings as error types

Result<T, String> is seductive because it needs no setup. The trouble is that the caller can only do two things with a String: print it, or compare its text. The second option is a trap.

Rust Stringly-typed errors are fragile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The string version works until a colleague changes "name is too long" to "name too long"; nothing warns you, and the truncation silently stops. The typed version carries the limit and the actual length as data, so the caller does not have to parse numbers back out of a sentence. Strings are acceptable when the error is meant only to be shown (for example in a one-file script), never when anything might act on it.

Rule 3: Let the compiler track the cases

An error enum is a contract. When you add a variant later, every exhaustive match in the program stops compiling until it handles the new case. That is exactly what you want in application code, because it forces a decision at every call site.

Rust Adding a variant breaks every match (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc answers with E0004 ("non-exhaustive patterns: &UploadError::QuotaExceeded not covered") and even suggests the missing arm. In a library the same freedom would be a problem, because adding a variant would break downstream users. Library authors mark such enums with #[non_exhaustive], which forces outside crates to include a wildcard arm so that new variants are not a breaking change (inside your own crate the attribute has no effect, so you will not see it in a single-file example).

Rule 4: Add context where you still have it

A low-level error knows what failed ("invalid digit found in string") but not why you were doing it ("reading the quantity of line 3 in orders.csv"). The context lives in the caller. Attach it at the point where the information exists, usually with map_err, and keep the original error as the source.

Rust Context makes errors actionable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare "invalid digit found in string" with "line 2: bad quantity (invalid digit found in string)". Only the second one lets you fix the file.

Two cautions. Do not add context twice at neighboring layers ("failed to load: failed to load config: failed to load config file...") or the output turns into noise; each layer should say something new. And do not discard the original error with map_err(|_| ...): the source is often the most precise part of the story.

Rule 5: Collect validation errors instead of stopping at the first

? stops at the first failure, which is perfect for dependent steps (you cannot parse a field you could not read). For validation of independent fields it is irritating: the user fixes one mistake, resubmits, and meets the next. Report all the problems at once by accumulating them in a Vec:

Rust Validating everything and reporting all problems

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error type here is Vec<Problem>, a collection, and each Problem is still a precise variant. Usually the collection is wrapped in its own struct (ValidationErrors) so it can implement Display and Error. The same idea scales to iterators: Iterator::partition, or fold into two vectors, splits a mixed sequence of results into successes and failures when you want to keep going after bad items.

Rule 6: Retry only what can succeed on retry

Not all failures are equal. A timeout may well work on the second attempt; a "permission denied" never will. A good error type makes the difference queryable, so retry logic does not have to guess:

Rust Retrying transient errors only

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first scenario recovers after two transient failures. The second stops at once, because Forbidden is permanent. The third gives up after the attempt limit and returns the last error. The fourth scenario, NotFound, is permanent too, so it stops after one call. Real retry loops add a delay that grows (100 ms, 200 ms, 400 ms, with some random jitter) and make sure the operation is idempotent, because retrying a request that half-succeeded can charge a customer twice.

Rule 7: Return or log, but not both

A very common anti-pattern is to log an error and also return it. The caller then logs it again, and its caller again, and one failure floods the log with five copies. The cleaner discipline is:

  • Low-level and library code returns errors, with context, and never prints them.
  • The code that finally handles the error (usually near main, or at a request boundary) decides: log it, show it to the user, retry, or exit.
Rust Report once, at the boundary (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The exit code 2 appears in the run notes below the output; picking different codes for different failure classes is how scripts tell what went wrong (see exit codes).

Rule 8: Libraries should (almost) never panic

A panic in a library is a decision to crash somebody else's program, taken without knowing what that program is. The rules of thumb:

  • If the input comes from outside and can be wrong, return a Result.
  • Panic only when the caller has violated a documented contract (for example, indexing out of bounds, which is how the standard library behaves) or when an internal invariant is broken, meaning your own code has a bug.
  • If you do panic on contract violations, say so in a # Panics section in the doc comment, and offer a non-panicking variant (get next to [], checked_add next to +).
  • Avoid unwrap on anything derived from input. Use expect("...") with a message when an invariant is truly guaranteed, so the crash message explains the broken assumption.
Rust A checked and a panicking variant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is the same shape the standard library uses everywhere: a method that returns Option or Result for careful callers, and a shorter one that panics for callers who have already checked. Pick the safe one as the primary API.

A practical checklist

  1. Who reads this error, a program or a person? Enum for programs, context-rich messages for people.
  2. Can the caller do something about it? If not, a boxed or anyhow error with context is enough.
  3. One layer, one message. Each error describes only its own step and links to its cause with source().
  4. Keep the cause. Do not throw the underlying error away with map_err(|_| ...).
  5. Validate together, depend sequentially. Accumulate independent problems; use ? for dependent steps.
  6. Make retry decisions queryable (is_transient), and never retry non-idempotent actions blindly.
  7. Report once, at the boundary. Return errors upward; log or print them in one place.
  8. No panics for bad input in reusable code. Document the ones you do keep.

When you are unsure, start with a small enum with two or three variants, a Display implementation and ?. Splitting or merging variants later is cheap because the compiler shows you every place that needs to change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is Result<T, String> a poor choice for a library's public API?

    A string carries no structure the caller can match on. An enum documents and enforces the possible failures.
  2. 2. What does adding a new variant to your error enum do to a match that has no wildcard arm?

    Exhaustiveness checking turns the new variant into error E0004 at every such match, which is the point of using an enum.
  3. 3. Which approach reports all invalid fields of a form in one go?

    ? returns at the first failure. Accumulating into a Vec lets you report everything that is wrong.
  4. 4. Where should an error usually be logged or shown to the user?

    Logging at every layer duplicates the report. Lower layers return errors with context; the boundary decides what to do.
  5. 5. Which failure is a good candidate for an automatic retry?

    Transient failures may succeed on a later attempt; permanent ones, such as permission or validation errors, will not.

Summary

  • Design errors for their reader: programs need enums to match on, people need clear messages with context.
  • Libraries expose precise error types (and #[non_exhaustive] when they may grow); applications can use Box<dyn Error> or anyhow and print the chain at the top.
  • Avoid String errors for anything a caller might act on; an enum lets the compiler check every case.
  • Add context where you still know it, once per layer, and keep the original cause as source().
  • Accumulate independent validation problems in a Vec; use ? for steps that depend on each other.
  • Expose queries like is_transient so retry logic is simple, and retry only idempotent operations.
  • Return errors from low-level code and report them once at the boundary. Reserve panics for broken invariants, and document them.

Next: Modules