skip to content

How should a Rust PaymentError::Network variant expose its wrapped io::Error, and why should its Display not print it too?

level: seniorimportance: should knowfreq 42%

answer

  1. abstraction boundaries
  2. Option<&(dyn Error + 'static)>
  3. source or Display, not both
  4. walk with while let

basics

~20 s

Override source() to return Some of the io::Error for Network and None otherwise, and keep Display to PaymentError's own message: std's docs say a wrapped error belongs in source() or in Display, not both, or every report prints it twice.

solid answer

~40 s

Implement `fn source(&self) -> Option<&(dyn Error + 'static)>` and match on `self`: `PaymentError::Network(e) => Some(e)`, every other variant `None`. The `&io::Error` coerces to the trait object because `io::Error` implements `Error` and holds no borrowed data, so it meets the `'static` bound. `Display` then says only what failed at this layer — "could not reach the payment gateway" — because std's `Error` docs say an underlying error should be returned by `source()` or rendered by `Display`, but not both. A reporter walks the chain with `while let Some(e) = cause { ...; cause = e.source(); }` and prints each layer once; if `Display` also embedded the `io::Error`, every report would show it twice. The iterator form, `sources()`, is still unstable.

code

rust · 39 lines
rust
use std::error::Error;
use std::fmt;
use std::io;

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

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::Network(_) => write!(f, "could not reach the payment gateway"),
            PaymentError::InvalidCard => write!(f, "card number failed validation"),
        }
    }
}

impl Error for PaymentError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            PaymentError::Network(e) => Some(e),
            _ => None,
        }
    }
}

fn main() {
    let err = PaymentError::Network(io::Error::new(io::ErrorKind::TimedOut, "connect timed out"));
    println!("error: {err}");
    let mut cause = err.source();
    while let Some(e) = cause {
        println!("caused by: {e}");
        cause = e.source();
    }
}

go deeper

for a junior

Recall that source() returns the error underneath, None by default, and that a reporter prints an error and then each of its sources.

for a middle

Explain the signature: a borrowed trait object, Option for no cause, and the 'static bound that keeps the source downcastable, plus the stable while let loop that walks it.

for a senior

Show you apply std's either/or rule so reports never duplicate text, and that you know where std's own io::Error wrapping hides a payload from the chain walk.

for a principal

Weigh which causes a crate exposes through source(): every exposed inner type can be downcast by callers, so the chain is part of what downstream code may come to depend on.

## Why errors form chains std's documentation for `Error::source()` says it is generally used when errors cross **abstraction boundaries**: a payment module reports its own failure ("could not reach the payment gateway") while still letting a caller reach the lower-level I/O failure that caused it. The result is a **source chain** — a linked list of errors, each pointing at the one below — that a reporter or a debugger can walk. ## The signature, decoded ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` - `&self` — the source is **borrowed** from the outer error, so walking a chain allocates nothing and moves nothing. - `Option` — `None` means "no underlying cause", which is the trait's default and the right answer for `Declined` and `InvalidCard`. - `dyn Error` — a **trait object**: the caller sees only the `Error` interface, whatever the concrete type is. - `'static` — the concrete type behind the trait object holds no borrowed data. That bound is what makes the source downcastable: `downcast_ref` is defined on `dyn Error + 'static`. The older `cause()` returned plain `&dyn Error`; its deprecation note (since 1.33) says it was replaced by `source`, which can support downcasting. ## Implementing it for `PaymentError` ```rust impl Error for PaymentError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { PaymentError::Network(e) => Some(e), _ => None, } } } ``` `e` is a `&io::Error`; returning it inside `Some` performs an **unsizing coercion** to `&(dyn Error + 'static)`. When a variant instead stores `Box<dyn Error + Send + Sync>`, return `Some(boxed.as_ref())`: `Box<dyn Error>` does not itself implement `Error` (std's impl is `impl<E: Error> Error for Box<E>`, which needs a sized `E`), so `Some(&self.0)` fails with E0277 and the inner trait object must be returned instead. ## Walking the chain On stable Rust a reporter walks the chain by hand: ```rust let mut cause = err.source(); while let Some(e) = cause { println!("caused by: {e}"); cause = e.source(); } ``` `dyn Error::sources()` returns an iterator over the same links, but it sits behind the unstable `error_iter` feature, so stable code uses the loop. Neither `to_string()` nor `{}` follows the chain: each prints only the `Display` of the error it is called on. ## The either/or rule std's `Error` docs state the rule directly: in error types that wrap an underlying error, the underlying error should be either returned by the outer error's `source()` or rendered by its `Display`, but not both. | Design | What a chain-walking report prints | |---|---| | `source()` returns it, `Display` omits it | each message once — the intended shape | | `Display` renders it, `source()` returns `None` | the text once, but the cause cannot be inspected or downcast | | both | the I/O message twice, once inside the outer message and once as `caused by:` | | neither | the cause is lost | Returning it from `source()` is usually the better half, because a caller can still inspect or downcast the inner `io::Error`; rendering it in `Display` suits a wrapper whose inner error is an implementation detail no caller should inspect. ## std follows the same rule `std::io::Error` built with `io::Error::new(kind, payload)` renders the payload in its `Display` and returns the **payload's own** `source()` from its `source()`. So if a `PaymentError` is wrapped in an `io::Error`, a chain walk starting at the `io::Error` never yields the `PaymentError` as a link: its text appears in the `io::Error`'s message instead. Reaching the payload itself takes `io::Error::get_ref()`. ## Testing the chain A unit test pins the contract so a later refactor cannot quietly drop the cause: ```rust #[test] fn network_error_exposes_io_source() { let err = PaymentError::Network(io::Error::new(io::ErrorKind::TimedOut, "connect timed out")); let io_err = err.source().and_then(|e| e.downcast_ref::<io::Error>()).expect("io source"); assert_eq!(io_err.kind(), io::ErrorKind::TimedOut); } ``` The test downcasts the source back to `io::Error` and checks its kind, which only works because `source()` returns a `'static` trait object. ## Mistakes to avoid 1. Formatting the inner error into `Display` ("network error: connect timed out") while also returning it from `source()`. 2. Implementing the deprecated `cause()` instead of `source()`. 3. Returning `Some(self)` — a self-loop that sends a chain walker round forever. 4. Writing `source()` on leaf errors that have no cause; the default `None` is already right.

  • Why does `source()` return `&(dyn Error + 'static)` rather than `&dyn Error`?
    The `'static` bound lets a caller downcast the source, because `downcast_ref` is defined only on `dyn Error + 'static`. The older `cause()` returned `&dyn Error`; its deprecation note since 1.33 says `source` replaced it because it can support downcasting. The bound means the concrete source type holds no borrowed data.
  • A `PaymentError` is wrapped with `io::Error::new(ErrorKind::Other, payment_err)`. What does walking `source()` from the `io::Error` show?
    Not the `PaymentError`. `io::Error`'s `Display` renders the payload's message, and its `source()` returns the payload's own `source()`, which is `None` for a decline. The `PaymentError` is reached with `io_err.get_ref()` followed by `downcast_ref::<PaymentError>()`.
  • A variant stores `Box<dyn Error + Send + Sync>`. Why does `Some(&self.0)` fail in `source()`?
    `&self.0` is a `&Box<dyn Error + Send + Sync>`, and `Box<dyn Error>` does not implement `Error`: std's impl is `impl<E: Error> Error for Box<E>`, which requires a sized `E`. rustc reports E0277 about the size of the trait object. Return `Some(self.0.as_ref())`, the inner trait object, instead.

An incident report whose cover page says "payment gateway unreachable" and staples the network team's report behind it: copying the network report's text onto the cover as well means anyone reading the stack reads it twice.

  • Display should include the underlying io::Error so nothing is lost.
  • Every error type must implement source() or the chain breaks.
  • cause() is the method to override to expose an inner error.
  • Calling sources() on stable Rust iterates the whole chain.
  • Printing an error with {} or to_string() shows all of its causes.