skip to content

How do you recover a concrete PaymentError from a Rust Box<dyn Error + Send + Sync> with downcast_ref, and when does it return None?

level: seniorimportance: should knowfreq 35%

answer

  1. TypeId comparison
  2. exact type, outermost only
  3. T: Error + 'static
  4. io::Error hides its payload

basics

~10 s

Call err.downcast_ref::<PaymentError>(), which checks whether the boxed value's concrete type is exactly PaymentError and returns Option<&PaymentError>; it returns None for any other type, including a wrapper whose source() is a PaymentError.

solid answer

~40 s

`downcast_ref::<T>()` is defined on `dyn Error + 'static` and its `+ Send` and `+ Send + Sync` forms, with `T: Error + 'static`. It compares the erased value's `TypeId` with `T`'s and returns `Option<&T>`, which you match like any `PaymentError`: `if let Some(PaymentError::Declined { code }) = err.downcast_ref::<PaymentError>()`. It inspects only the outermost error, so a `PaymentError` sitting in some wrapper's `source()` gives `None` until you walk the chain and try each link. The by-value form, `downcast::<T>()` on the box, returns `Result<Box<T>, Box<...>>` and hands the box back on a miss. Types that do not implement `Error` cannot be targets — `downcast_ref::<String>()` fails with E0277 — and a payload inside `io::Error::new` can be reached by calling `io::Error::get_ref()` first.

code

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

#[derive(Debug)]
pub enum PaymentError {
    Declined { code: u16 },
    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::InvalidCard => write!(f, "card number failed validation"),
        }
    }
}

impl Error for PaymentError {}

fn checkout(step: u8) -> Result<(), Box<dyn Error + Send + Sync>> {
    match step {
        0 => Err(PaymentError::Declined { code: 51 }.into()),
        1 => Err(io::Error::new(io::ErrorKind::TimedOut, "gateway timed out").into()),
        _ => Err("cart is empty".into()),
    }
}

fn main() {
    for step in 0..3 {
        let err = checkout(step).unwrap_err();
        if let Some(PaymentError::Declined { code }) = err.downcast_ref::<PaymentError>() {
            println!("declined with code {code}: ask for another card");
        } else if let Some(io_err) = err.downcast_ref::<io::Error>() {
            println!("retryable: {:?}", io_err.kind());
        } else {
            println!("other: {err}");
        }
    }
}

go deeper

for a junior

Recall that downcast_ref::<T>() turns a boxed error back into an Option<&T>, returning Some only when the value really is that type.

for a middle

Explain the bounds T: Error + 'static, the difference between downcast_ref and the by-value downcast on a Box, and why only the outermost error is checked.

for a senior

Show you handle the real cases: walking source() to find a wrapped type, reaching io::Error payloads with get_ref, and keeping a Display fallback when nothing matches.

for a principal

Argue where type erasure belongs: downcasting at an application's top level is fine, but a library that forces callers to downcast has hidden its failure contract.

## What downcasting does A `Box<dyn Error + Send + Sync>` has **erased** its concrete type: code holding it sees only the `Error` interface. **Downcasting** asks "is the value in here exactly type `T`?" and, if so, gives back a typed reference. std provides the methods directly on the error trait object: - `is::<T>()` returns `bool`. - `downcast_ref::<T>()` returns `Option<&T>`. - `downcast_mut::<T>()` returns `Option<&mut T>`. - `downcast::<T>()` on the box returns `Result<Box<T>, Box<dyn Error ...>>`, consuming the box and returning it unchanged on a miss. The first three are defined on `dyn Error + 'static`, with forwarding versions for `+ Send` and `+ Send + Sync`, and all four require `T: Error + 'static`. Internally `is` compares the `TypeId` of `T` with the `TypeId` reported by the trait object; `Error::type_id` is deliberately impossible to override from user code, because a lying override would make the cast unsound. ## Recovering `PaymentError` ```rust if let Some(PaymentError::Declined { code }) = err.downcast_ref::<PaymentError>() { println!("declined with code {code}: ask for another card"); } else if let Some(io_err) = err.downcast_ref::<io::Error>() { println!("retryable: {:?}", io_err.kind()); } ``` Method-call auto-deref lets you call `downcast_ref` on the `Box` itself; the call lands on the `dyn Error + Send + Sync` inside. The pattern then destructures the recovered enum exactly as it would a `PaymentError` returned directly. ## When it returns `None` 1. **The outermost error is another type.** Downcasting is an exact type test; there is no subtyping between error types. 2. **The `PaymentError` is further down the chain.** `downcast_ref` never calls `source()`. To find it anywhere, walk the links: start with `Some(&*err)`, try `downcast_ref` on each, and step with `e.source()` until `None`. 3. **The payload went into an `io::Error`.** An `io::Error` built with `io::Error::new(kind, payment_err)` is itself the outer type, so `downcast_ref::<PaymentError>()` on it fails — and walking `source()` does not help either, because `io::Error::source()` returns the payload's own source, not the payload. Call `io_err.get_ref()`, which returns `Option<&(dyn Error + Send + Sync + 'static)>`, and downcast that. Two related cases fail to **compile** rather than return `None`: - `downcast_ref::<String>()` — `String` does not implement `Error`, so rustc reports E0277: the trait `std::error::Error` is not implemented for `String`. A box made from a `String` holds a private wrapper type, so its text can be displayed but never recovered by type. - A target type that borrows data, such as `struct ParseError<'a> { input: &'a str }`, cannot meet the `'static` bound when `'a` is shorter than `'static`. `TypeId::of` is itself defined only for `'static` types, so the bound carries over to every downcast method. ## Taking ownership with `downcast` When the handler needs to keep the concrete error — to store it, return it or move it into another error — use the by-value form on the box: ```rust match err.downcast::<PaymentError>() { Ok(payment) => println!("payment failure: {payment}"), Err(other) => println!("unrelated failure: {other}"), } ``` On success it yields a `Box<PaymentError>`; on a miss the `Err` holds the original box, still `Send + Sync`, so nothing is lost and the next check can run on it. ## Choosing the right tool | Situation | Use | |---|---| | A library function's callers must branch on failures | return `PaymentError` and let them `match` | | Application top level holding a catch-all box | `downcast_ref` for the few types that change behaviour | | You need to take ownership of the concrete error | `downcast` on the box, keeping the `Err` box on a miss | | You only need to know the kind | `is::<T>()` | Downcasting is a recovery tool for code that chose type erasure, typically an application's top level or a plugin boundary. It is not a substitute for a typed error at a library's API: callers cannot see from a signature which concrete types might be inside a box, and nothing warns them when a library starts returning a different one. ## Checklist - Make the target type `'static` and implement `Error` for it. - Test the outermost value first, then walk `source()` if the type may be wrapped. - Reach into `io::Error` payloads with `get_ref()` (or `into_inner()` to take ownership). - Keep a fallback arm that reports the error by its `Display` when no downcast matches.

  • How do you find a `PaymentError` anywhere in a chain, not only at the top?
    Walk the links and test each one: `let mut cur: Option<&(dyn Error + 'static)> = Some(&*err); while let Some(e) = cur { if let Some(p) = e.downcast_ref::<PaymentError>() { return Some(p); } cur = e.source(); }`. Each `source()` result is already `dyn Error + 'static`, so every link can be downcast.
  • Why does `err.downcast_ref::<String>()` not compile on a box built from a `String`?
    `downcast_ref` requires `T: Error + 'static`, and `String` does not implement `Error`, so rustc reports E0277. The `From<String>` impl for the boxed error wraps the text in a private type, so the message can be displayed with `{err}` but never recovered as a typed `String`.

  • downcast_ref searches the whole source chain for the requested type.
  • A Box<dyn Error> built from a String can be downcast back to String.
  • An error type borrowing a short-lived &'a str can still be downcast.
  • Downcasting a boxed error is how a library's callers should branch on failures.
  • downcast_ref::<PaymentError>() on an io::Error wrapper returns the payload.