skip to content

What must a Rust error enum implement to satisfy std::error::Error, and what does rustc report when Display is missing?

level: middleimportance: must knowfreq 62%

answer

  1. two supertraits
  2. Debug derived, Display hand-written
  3. every Error method has a default
  4. E0277 on the impl line

basics

~20 s

std::error::Error has Debug and Display as supertraits and gives every method a default, so derive Debug, write Display by hand and add an empty impl block; without Display, rustc stops with E0277: PaymentError doesn't implement std::fmt::Display.

solid answer

~40 s

`std::error::Error` is declared `pub trait Error: Debug + Display`, and every method has a default: `source()` returns `None`, `description()` and `cause()` are deprecated, and `provide()` is unstable. So the minimum is `#[derive(Debug)]`, a hand-written `impl fmt::Display` — std has no derive for `Display` — and `impl std::error::Error for PaymentError {}`. Leave out `Display` and rustc rejects the empty impl with E0277, `` `PaymentError` doesn't implement `std::fmt::Display` ``, with a note that the bound comes from `std::error::Error`. `Display` is the message for users and logs, which std's docs describe as typically a concise lowercase sentence without trailing punctuation; `Debug` is what `unwrap`, `expect` and a `main` returning `Err` print.

code

rust · 14 lines
rust
use std::error::Error;

#[derive(Debug)]
pub enum PaymentError {
    Declined { code: u16 },
    InvalidCard,
}

impl Error for PaymentError {}

fn main() {
    let e = PaymentError::Declined { code: 51 };
    println!("{e:?}");
}

go deeper

for a junior

Recall the three pieces: derive Debug, write Display by hand, and add an empty impl std::error::Error block; know that both Debug and Display are required.

for a middle

Explain why the impl block can be empty: Debug and Display are supertraits and every Error method has a default, with description and cause deprecated and provide unstable.

for a senior

Show you read E0277 output quickly, keep Display and Debug for different audiences, and follow std's message convention so chained reports read as one consistent sentence per layer.

for a principal

Treat Display wording as user-facing surface: messages land in logs and support tickets, so a team convention for tone and content pays off more than any single impl.

## The trait's declaration The standard library defines the error trait in `core::error` and re-exports it as `std::error::Error`: ```rust pub trait Error: Debug + Display { fn source(&self) -> Option<&(dyn Error + 'static)> { None } // plus deprecated and unstable methods, all with default bodies } ``` `Debug + Display` after the colon makes both traits **supertraits**: a type may implement `Error` only if it already implements `std::fmt::Debug` and `std::fmt::Display`. Everything inside the trait body has a default, so once both supertraits exist the impl block can be empty. std's own doc comment says it plainly: implementing `Error` only requires that `Debug` and `Display` are implemented too. ## Every method and its default | Method | Status on stable 1.99 | Default behaviour | |---|---|---| | `source()` | stable | returns `None` | | `description()` | deprecated since 1.42 | returns a fixed placeholder string; use `Display` or `to_string()` | | `cause()` | deprecated since 1.33 | forwards to `source()`, which replaced it | | `provide()` | unstable | does nothing | | `type_id()` | unstable and hidden | returns the type's `TypeId`; it cannot be overridden from user code | The practical consequence: on stable Rust the only method you ever write is `source()`, and only when the error wraps a lower-level cause. ## A complete minimal impl 1. **Debug** — add `#[derive(Debug)]`. The generated output (`Declined { code: 51 }`) is for developers. 2. **Display** — write it by hand, because std ships derives for `Debug`, `Clone`, `PartialEq` and friends but not for `Display`. Match on `self` and `write!` one message per variant. 3. **Error** — `impl std::error::Error for PaymentError {}`. ```rust impl fmt::Display for PaymentError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PaymentError::Declined { code } => write!(f, "payment declined (code {code})"), PaymentError::InvalidCard => write!(f, "card number failed validation"), } } } impl std::error::Error for PaymentError {} ``` Derive crates can generate the `Display` and `Error` impls from attributes; they are a separate subject, covered with library and application error strategies. Writing the impls by hand shows exactly what such a derive generates. ## What rustc says when a piece is missing Without the `Display` impl, rustc 1.99.1 points at the empty `impl Error` line and reports E0277: `` `PaymentError` doesn't implement `std::fmt::Display` ``, followed by a note that the bound is required by `std::error::Error`, at the `Display` in `pub trait Error: Debug + Display`. Drop the `#[derive(Debug)]` instead and the same E0277 appears for `Debug`. Neither omission is a warning, and neither is reported where the error is later used: the impl itself is rejected. ## Writing a good `Display` - **Lowercase, no trailing punctuation.** std's docs describe error messages as typically concise lowercase sentences without trailing punctuation (`"invalid digit found in string"` is std's own example). Such a message reads well when a reporter prints it after `error:` or `caused by:`. - **Say what failed at this layer.** "payment declined (code 51)" names the operation and the key datum. - **Do not repeat a wrapped error.** If a variant wraps an `io::Error` and `source()` returns it, `Display` should not print it as well; std's docs say a wrapped error belongs in one or the other, not both. - **Keep `Debug` for developers.** `Result::unwrap` and `expect` require `E: Debug` and print the `Debug` form, and a `main` that returns `Err` prints `Error: ` followed by the `Debug` output. ## How each piece is used Once the three impls exist, different parts of std and the ecosystem pick different pieces: - `{}`, `to_string()` and `write!` with `{}` use **`Display`** — this is what users and logs see. - `{:?}`, `unwrap()`, `expect()` and `dbg!` use **`Debug`** — this is what developers see when something blows up. - `Box<dyn Error>` and `Box<dyn Error + Send + Sync>` accept the value through std's `From` impls, which require `Error`. - Chain-walking reporters call **`source()`** on each layer and print each layer's `Display`. So a type that implements only `Debug` and `Display` prints fine but cannot be boxed as an error or appear as anyone's `source()`; the empty `impl Error` block is what unlocks those. ## Common mistakes - Expecting a `#[derive(Error)]` or `#[derive(Display)]` from std — neither exists in std. - Implementing `description()` to supply the message. It has been deprecated since 1.42, and its deprecation note says to use the `Display` impl or `to_string()` instead. - Believing `source()` must be written for the impl to compile. Its default returns `None`, which is correct for an error with no underlying cause. - Putting user-facing text in `Debug` and leaving `Display` terse. Reporters show `Display`; `Debug` is for diagnosis.

  • Why does it matter in practice that `Debug` is a supertrait of `Error`?
    It guarantees every error value can be printed by the code paths that only know `E: Debug`: `Result::unwrap` and `expect` require it to format the panic message, and a `main` returning `Result<(), E>` prints `Error: {err:?}` on failure. Any `E: Error` therefore works with all of them without extra bounds.
  • Should `PaymentError`'s `Display` start with a capital letter and end with a period?
    Conventionally no. std's `Error` docs say messages are typically concise lowercase sentences without trailing punctuation, and its own example is "invalid digit found in string". Such messages read cleanly when a reporter prefixes them with `error:` or lists them as `caused by:` lines.

  • std provides #[derive(Error)] and #[derive(Display)] just like #[derive(Debug)].
  • You must implement source() or the Error impl will not compile.
  • Implementing description() is how an error supplies its message.
  • Debug output is what end users should see in error messages.
  • A missing Display impl only produces a warning until the error is printed.