skip to content

Library vs Application Failures

Libraries return typed errors callers can match, applications usually want one catch-all error with context. Interviewers ask when to reach for thiserror and when for anyhow.

on this pageshow

questions

5

In Rust, when do you reach for thiserror and when for anyhow, and what does each give the code that receives the error?

level: middleimportance: must knowfreq 70%

answer

  1. who consumes the failure
  2. matchable enum vs opaque wrapper
  3. a derive for std::error::Error
  4. getting the type back means downcasting

basics

~20 s

thiserror derives std::error::Error for your own enum, so callers can match on its variants: the usual library choice. anyhow::Error wraps any error in one opaque type that is easy to propagate and print: the usual application choice.

solid answer

~40 s

It depends on who consumes the failure. A library's caller often has to react (retry on a timeout, return 404 on not-found), so the library returns its own error enum, and `#[derive(thiserror::Error)]` writes the `Display`, `Error::source` and `From` impls a hand-written enum would need. The caller gets an exhaustive `match`, and thiserror never shows up in the public API. An application mostly propagates and reports. With `anyhow::Result<T>`, `?` accepts any `std::error::Error + Send + Sync + 'static`, `bail!` and `ensure!` build one-off errors, and `main` prints the error with its causes. The cost is that `anyhow::Error` is opaque: the only way back to a concrete type is downcasting, such as `downcast_ref`, and the compiler cannot check it. Many codebases use both, thiserror in the storage crate and anyhow in the binary.

go deeper

for a junior

Recall the one-line rule: thiserror helps you define your own error type, while anyhow gives you one ready-made error type for propagating anything with ?.

for a middle

Explain what each choice gives the caller: compile-time matching on variants versus an opaque value you have to downcast. Mention that thiserror's impls are ordinary code, so it never leaks into your public API.

for a senior

Show that you have lived with both. Branch on the typed error before lifting it into anyhow, and treat a downcast_ref the compiler cannot verify as a runtime contract to keep to a minimum.

for a principal

Frame it as the API surface of each crate: which consumers need to act on failure kinds, how much a variant costs to maintain, and where in the workspace typed errors turn into opaque reports.

## The decision turns on who consumes the error Rust has no exceptions. A fallible function returns `Result<T, E>`, and the **error type `E` is part of its signature**. So choosing between thiserror and anyhow is really choosing what that `E` promises the caller: - **thiserror** is a derive macro. You still define your own error type, usually an enum, and the derive writes the `std::error::Error` boilerplate for it. The caller sees a concrete type with named variants. - **anyhow** gives you a single type, `anyhow::Error`, that can hold *any* error implementing `std::error::Error + Send + Sync + 'static`. The caller sees one opaque type whatever went wrong. The thiserror README puts it this way: use thiserror "if you care about designing your own dedicated error type(s) so that the caller receives exactly the information that you choose", which "most often applies to library-like code", and use anyhow "if you don't care what error type your functions return, you just want it to be easy", which is "common in application-like code". ## What thiserror gives a library's callers Picture a storage crate used by a web service. The service must answer 404 for a missing record and 500 for a broken disk, so it needs to tell those apart: ```rust #[derive(Debug, thiserror::Error)] pub enum StorageError { #[error("record {id} not found")] NotFound { id: u64 }, #[error("storage I/O failed")] Io(#[from] std::io::Error), } ``` - **Exhaustive matching.** The caller writes `match err { StorageError::NotFound { .. } => 404, StorageError::Io(_) => 500 }`, and the compiler checks the match is exhaustive. - **Generated impls.** `#[error("...")]` becomes `Display`, `#[from]` becomes a `From<std::io::Error>` impl and the value returned by `source()`. - **No dependency leak.** The README says thiserror "deliberately does not appear in your public API". The output is the same as hand-written impls, and switching between the two is not a breaking change. ## What anyhow gives an application A binary usually just needs failures to travel up and be reported well: - `anyhow::Result<T>` is an alias for `Result<T, anyhow::Error>`. - `?` converts any qualifying error through anyhow's blanket `impl<E> From<E> for anyhow::Error`, so one function can propagate an `io::Error`, a `ParseIntError` and a `StorageError` without writing any conversions. - `bail!` and `ensure!` create one-off errors from a message. - Returning `anyhow::Result<()>` from `main` prints `Error: ...` followed by the cause chain. The original error is not thrown away. It sits inside the `anyhow::Error`, and `err.downcast_ref::<StorageError>()` returns `Some` when that is the type inside. But nothing in the signature says which types might be in there. ## Side by side | | thiserror enum | `anyhow::Error` | |---|---|---| | Who defines the type | you, one per crate or module | anyhow, one type for everything | | Caller distinguishes failures by | `match` on variants, checked at compile time | `downcast_ref`, checked at run time | | Cost of a new failure kind | add a variant | nothing, any error converts | | Implements `std::error::Error` | yes | no (it derefs to `dyn Error` instead) | | Typical home | library crates | binaries, scripts, top-level glue | ## Using both in one workspace The two crates are complementary rather than competing: 1. The storage crate returns `Result<T, StorageError>` built with thiserror. 2. The binary's functions return `anyhow::Result<T>`, and `?` lifts a `StorageError` into `anyhow::Error`, because a derived enum with `Send + Sync + 'static` fields meets the blanket `From` bound. 3. Code that needs to branch on a storage failure does so *before* lifting it, while the typed `Result` is still in hand. ## Common misreadings - "Libraries thiserror, binaries anyhow" is a default, not a law. A binary can derive its own error enum, and an internal crate with a single consumer that only reports errors can reasonably use anyhow. - anyhow does not erase the error. Its message, its `source()` chain and its concrete type all survive, but you can only get the type back by downcasting. - thiserror adds no runtime machinery. It generates ordinary trait impls at compile time. - The two are not alternatives for the same job. thiserror helps you *define* an error type; anyhow *is* an error type. A project can use neither, either or both.

  • Does deriving errors with thiserror in a library force its callers to depend on thiserror?
    No. The derive expands to ordinary `Display`, `std::error::Error` and `From` impls inside your crate. The thiserror README says it "deliberately does not appear in your public API", and switching between the derive and hand-written impls is not a breaking change. Callers see only your enum and std traits.
  • Can a function returning `anyhow::Result` call a library that returns a thiserror enum and use `?` on it?
    Yes. anyhow has a blanket `impl<E> From<E> for anyhow::Error` where `E: std::error::Error + Send + Sync + 'static`, and a derived enum meets it as long as its fields are `Send + Sync + 'static`. The concrete enum is kept inside, so `downcast_ref::<StorageError>()` can get it back later.
  • Is anyhow in a library always wrong?
    No. The cost falls on callers: there are no variants to match, and the error type does not implement `std::error::Error`. An internal crate whose only consumer reports errors, or a test helper, can use anyhow reasonably. The line to draw is whether any caller needs to branch on what kind of failure happened.

A typed error is a form with labelled checkboxes the next desk can sort by at a glance; anyhow::Error is a sealed envelope with a note on the front: easy to pass along and read aloud, but to route it you must open it and hope it holds what you expect.

  • A binary must never derive its own error types with thiserror.
  • Callers can match directly on an anyhow::Error's original variants.
  • Using thiserror makes thiserror part of the library's public API.
  • Converting to anyhow::Error keeps only the message; the original error is lost.
  • anyhow and thiserror cannot both appear in one dependency graph.
open as a page

In a Rust application using anyhow, what do bail! and ensure! do, and why can one function use ? on both io::Error and ParseIntError?

level: juniorimportance: should knowfreq 45%

basics

~20 s

bail!(...) returns early with Err(anyhow!(...)), and ensure!(cond, ...) does the same when cond is false. Both need a Result<_, anyhow::Error> return type. ? accepts both error types because anyhow::Error implements From for every std::error::Error + Send + Sync + 'static.

open as a page

In Rust, what does #[derive(thiserror::Error)] generate from #[error("...")] and #[from], and which uses of #[from] fail to compile?

level: middleimportance: should knowfreq 50%

basics

~10 s

The derive writes Display from each #[error("...")] string, std::error::Error with source() returning the #[from] or #[source] field, and one From impl per #[from] field. Two #[from] fields of one type conflict with E0119.

open as a page

A Rust storage crate's public functions return anyhow::Result; what breaks for the web service calling it, and why doesn't anyhow::Error implement std::error::Error?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Callers lose typed matching: they must downcast_ref to an internal type, and that call keeps compiling after the crate stops producing it. anyhow::Error cannot implement std::error::Error because its blanket From would overlap core's impl<T> From<T> for T.

open as a page

You lead a Rust workspace with a storage crate, a domain crate and a web service binary: what error strategy do you set across the crates, and where do errors convert?

level: principalimportance: should knowfreq 30%

basics

~20 s

Library crates return thiserror enums whose variants are the failures callers act on, wrapping dependency errors instead of exposing them. The binary uses anyhow internally and converts everything at one boundary type that decides the response.

open as a page