skip to content

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%

answer

  1. three impls, Debug not among them
  2. format string becomes Display
  3. from implies source
  4. one From per source type

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.

solid answer

~40 s

For each variant, `#[error("...")]` becomes an arm of a generated `Display` impl. `{id}` and `{0}` interpolate fields, and `{0:?}` uses their `Debug`. The derive also implements `std::error::Error`, whose `source()` returns the field marked `#[source]`, named `source`, or marked `#[from]`, since `#[from]` implies `#[source]`. Each `#[from]` field also gets an `impl From<FieldType> for YourError`, so `?` converts it. The derive does not write `Debug`: you still need `#[derive(Debug)]`, or rustc reports E0277. What fails: one variant left without `#[error]` while others have it (`missing #[error("...")] display attribute`); a `#[from]` variant with other fields (`deriving From requires no fields other than source and backtrace`); and two variants with `#[from]` on the same type, which produce two `From` impls and E0119. `#[error(transparent)]` forwards `Display` and `source()` to the variant's single field.

code

rust · 25 lines
rust
use std::error::Error as _;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum StorageError {
    #[error("record {id} not found")]
    NotFound { id: u64 },
    #[error("record {0} is corrupt: {1}")]
    Corrupt(u64, String),
    #[error("storage I/O failed")]
    Io(#[from] std::io::Error),
}

fn read_page(path: &str) -> Result<Vec<u8>, StorageError> {
    // io::Error -> StorageError::Io through the generated From impl
    let bytes = std::fs::read(path)?;
    Ok(bytes)
}

fn main() {
    println!("{}", StorageError::NotFound { id: 7 });
    println!("{}", StorageError::Corrupt(3, "bad checksum".into()));
    let e = read_page("/nonexistent/page.db").unwrap_err();
    println!("{e} / source: {}", e.source().unwrap());
}

go deeper

for a junior

Recall the three pieces: #[error] gives Display, #[from] gives a From impl so ? works, and you still derive Debug yourself.

for a middle

Explain that #[from] implies #[source], and why a #[from] variant cannot carry extra fields: From::from receives only the source value.

for a senior

Show you can design around the derive's limits: #[source] plus map_err for two variants sharing one source type, and transparent for a catch-all variant.

for a principal

Point out that the derive is an implementation detail callers never see, so the real design work is choosing the variants and which source types to expose.

## What the derive expands to `thiserror::Error` is a procedural derive macro. It reads your struct or enum together with its attributes and emits ordinary trait impls, the same code you would otherwise write by hand: - **`Display`**, built from the `#[error("...")]` attribute on the struct or on each enum variant, when you provide those attributes. - **`std::error::Error`**, with a `source()` method when some field is a source. - **`From<T>`**, one impl for each field marked `#[from]`. The derive works on enums, structs with named fields, tuple structs and unit structs. On a struct, the `#[error("...")]` attribute sits on the struct itself; on an enum, it sits on each variant. Because the output is plain trait impls, the README notes that thiserror "deliberately does not appear in your public API", and that replacing the derive with hand-written impls, or the reverse, is not a breaking change for callers. It does **not** generate `Debug`. The standard trait is declared `pub trait Error: Debug + Display`, so you derive or write `Debug` yourself. Leave it off and rustc reports E0277 with the message "`StorageError` doesn't implement `Debug`". ## Format strings in `#[error]` The message accepts shorthand for fields, which expands to a `write!` on the formatter: - `#[error("{id}")]` writes `self.id` with `Display`. - `#[error("{0}")]` writes the first tuple field. - `#[error("{id:?}")]` and `#[error("{0:?}")]` use the field's `Debug`. - Extra format arguments are allowed, and inside them `.field` or `.0` refers to a field, as in `#[error("bad index {}", .idx)]`. Once any variant of an enum has an `#[error]` attribute, every variant needs one (or `#[error(transparent)]`); a variant left out fails with `missing #[error("...")] display attribute`. Leave the attribute off every variant and the derive skips `Display`, so you write that impl yourself. The generated `Display` prints **only** the format string. A variant declared `#[error("storage I/O failed")] Io(#[from] std::io::Error)` displays as `storage I/O failed`, and the `io::Error` is reached through `source()`. Reporting the whole chain is the job of whoever prints the error. ## `#[from]` and `#[source]` - `#[source]` marks the field that `source()` returns. A field **named** `source` is picked up without the attribute. - `#[from]` does two things. It marks the field as the source, so you never write both attributes, and it generates `impl From<FieldType> for YourError`. That `From` impl is what lets `?` turn a `std::io::Error` into `StorageError::Io` automatically. - A source must be a type that implements `std::error::Error` or dereferences to `dyn std::error::Error`. - A source cannot borrow with a non-`'static` lifetime, because `source()` returns `&(dyn Error + 'static)`. ## What fails to compile | Code | What rustc reports | |---|---| | enum without `#[derive(Debug)]` | `E0277`, "`StorageError` doesn't implement `Debug`" | | one variant without `#[error]` while others have it | `missing #[error("...")] display attribute` | | `Io { #[from] source: io::Error, path: String }` | "deriving From requires no fields other than source and backtrace" | | `Read(#[from] io::Error)` and `Write(#[from] io::Error)` | `E0119`, conflicting implementations of `From<std::io::Error>` | | `#[error(transparent)]` on a variant with two fields | "#[error(transparent)] requires exactly one field" | The extra-field rule follows from what `From` is: `From::from(io_error)` receives only the `io::Error` and has nowhere to get a `path` from. The duplicate rule is plain coherence: two impls of `From<std::io::Error>` for one type overlap. (A `Backtrace` field is the one extra a `#[from]` variant may carry, and it belongs with the material on backtraces.) ## Two variants with the same source type A storage crate may need `Read` and `Write` to be separate variants even though both wrap `io::Error`. In that case: 1. Mark both fields `#[source]` instead of `#[from]`. 2. Choose the variant explicitly at each call site, for example `file.read_to_end(&mut buf).map_err(StorageError::Read)?`. A tuple variant's constructor works as a function. 3. Keep `#[from]` for the single source type that has an obvious variant, if there is one. The same approach handles a variant that needs extra data, such as the path that failed. Drop `#[from]`, keep `#[source]`, and build the variant in `map_err`. ## `#[error(transparent)]` `#[error(transparent)]` forwards both `Display` and `source()` straight to the single field, without adding a message of its own. It suits a catch-all variant such as `Other(#[from] anyhow::Error)`, or a public newtype that wraps a private representation. With `transparent` the variant must have exactly one field, and it cannot also carry `#[source]`.

  • Why does thiserror's derive not also generate `Debug`?
    `std::error::Error` requires both `Debug` and `Display`. thiserror builds `Display` from your `#[error]` strings and leaves `Debug` to the usual `#[derive(Debug)]` or a hand-written impl. If you forget it, rustc rejects the derived `Error` impl with E0277: "`StorageError` doesn't implement `Debug`".
  • How do you keep an `io::Error` as the source while also storing the path that failed?
    Drop `#[from]`. Put `#[source]` on the `io::Error` field next to a `path` field, and build the variant with `map_err(|e| StorageError::Io { source: e, path: p.into() })`. `#[from]` is rejected there because a generated `From<io::Error>` could not fill in `path`: "deriving From requires no fields other than source and backtrace".

  • thiserror also derives Debug, so #[derive(Debug)] is redundant.
  • A #[from] variant can carry extra fields; the derive fills them with defaults.
  • Two variants can both use #[from] io::Error; ? picks the first one.
  • #[from] and #[source] must both be written on the same field.
  • The derived Display automatically appends the source error's message.