skip to content

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%

answer

  1. the signature promises nothing
  2. a downcast checked only at run time
  3. E0277 on an E: Error bound
  4. overlap with From<T> for T

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.

solid answer

~40 s

With `anyhow::Result` as the return type, the signature names one opaque type, so the service cannot `match` on not-found versus a broken disk. It has to call `err.downcast_ref::<storage::NotFound>()`, a check made at run time. If the crate later changes `bail!(NotFound { id })` to a plain message, the downcast still compiles, returns `None`, and the 404 quietly becomes a 500. The type also fails generic code: passing it where `E: std::error::Error` is required is E0277, because anyhow::Error does not implement the trait. It can't: anyhow has `impl<E: std::error::Error + Send + Sync + 'static> From<E> for anyhow::Error`, and if anyhow::Error were itself an `Error`, that impl would cover `From<anyhow::Error>` and overlap core's `impl<T> From<T> for T`. The fix is a thiserror enum at the crate boundary.

code

rust · 30 lines
rust
mod storage {
    use thiserror::Error;

    #[derive(Debug, Error)]
    #[error("record {id} not found")]
    pub struct NotFound {
        pub id: u64,
    }

    // The signature promises only "some error".
    pub fn load(id: u64) -> anyhow::Result<String> {
        if id == 1 {
            return Ok("alice".into());
        }
        anyhow::bail!(NotFound { id })
    }
}

fn status_for(id: u64) -> u16 {
    match storage::load(id) {
        Ok(_) => 200,
        // Compiles whether or not load() ever produces a NotFound.
        Err(e) if e.downcast_ref::<storage::NotFound>().is_some() => 404,
        Err(_) => 500,
    }
}

fn main() {
    println!("{} {}", status_for(1), status_for(9));
}

go deeper

for a junior

Recall that anyhow::Result in a function signature tells callers nothing about which failures can happen.

for a middle

Explain that downcast_ref is a runtime type check, and show the E0277 you get when an anyhow::Error meets an E: std::error::Error bound.

for a senior

Diagnose the silent 404-to-500 regression, explain the coherence overlap with From<T> for T, and fix the boundary with a thiserror enum plus a transparent catch-all.

for a principal

Treat every cross-crate downcast as an undeclared API contract, and set a review rule that public library functions never return anyhow::Result.

## The symptom in the calling service Suppose a storage crate exposes `pub fn load(id: u64) -> anyhow::Result<String>`, and the web service has to answer **404** for a missing record and **500** for everything else. The signature only says "some error". The service therefore writes: ```rust match storage::load(id) { Ok(_) => 200, Err(e) if e.downcast_ref::<storage::NotFound>().is_some() => 404, Err(_) => 500, } ``` This works today, but it rests on a promise the compiler cannot see. ## Why the downcast is fragile `anyhow::Error::downcast_ref::<E>()` is generic over **any** `E: Display + Debug + Send + Sync + 'static`. At run time it compares type identities and returns `Some` only when an `E` is stored inside. Follow what happens over the crate's lifetime: 1. The crate author refactors `bail!(NotFound { id })` into `bail!("record {id} not found")`, which is a perfectly reasonable change when the signature is `anyhow::Result`. 2. The service still compiles, since `downcast_ref::<NotFound>()` is valid for any `'static` error type. 3. At run time the downcast returns `None`, and every missing record is now reported as a 500. 4. Nothing failed in either crate's build. Only an integration test or a production report shows the change. A typed signature would have turned step 1 into a compile error at the service's `match`. With `pub fn load(id: u64) -> Result<String, StorageError>`: - the service matches `StorageError::NotFound { .. }`, and removing or renaming that variant breaks the service's build instead of its behaviour; - an exhaustive `match` makes every failure kind visible in the code that handles it; - the crate's documentation lists the failure kinds, because they are part of the type. ## `anyhow::Error` is not `std::error::Error` The second break shows up in generic code. A helper such as `fn report<E: std::error::Error>(e: E)`, or any API bounded on `E: Error`, rejects the value: ```plaintext error[E0277]: the trait bound `anyhow::Error: std::error::Error` is not satisfied ``` The reason is **coherence**, Rust's rule that two trait impls must never overlap: - anyhow needs `impl<E> From<E> for anyhow::Error where E: std::error::Error + Send + Sync + 'static`. That impl is what lets `?` absorb any error. - core has `impl<T> From<T> for T`. - If `anyhow::Error` implemented `std::error::Error`, the first impl would also cover `From<anyhow::Error> for anyhow::Error`, which is exactly what the second impl already provides. The two impls would overlap. You can reproduce the conflict with any local wrapper type: ```rust impl<E: Error + Send + Sync + 'static> From<E> for AppError { /* ... */ } impl Error for AppError {} // error[E0119]: conflicting implementations of trait `From<AppError>` for type `AppError` // = note: conflicting implementation in crate `core`: impl<T> From<T> for T; ``` anyhow gives up the `Error` impl to keep the blanket `From`. ## What still interoperates The type is not walled off. It just isn't usable as an `E: Error`: - It implements `Deref<Target = dyn std::error::Error + Send + Sync + 'static>`, so `e.source()` and other trait methods work through the deref. - It implements `AsRef<dyn std::error::Error + Send + Sync>` and `AsRef<dyn std::error::Error>`. - It converts with `.into()` or `?` into `Box<dyn std::error::Error + Send + Sync + 'static>`, and into the `Send`-only and plain boxed forms. - thiserror accepts it as a source field. Its README shows `#[error(transparent)] Other(#[from] anyhow::Error)`, because thiserror takes any source that implements `Error` or derefs to `dyn Error`. ## The fix at the crate boundary | Situation | Public error type | |---|---| | callers branch on a few failure kinds | a thiserror enum with those variants | | the crate also has many incidental failures | the same enum plus `#[error(transparent)] Other(#[from] anyhow::Error)` | | failure kinds still evolving, external consumers | an opaque struct over a private enum, with accessor methods | The Rust API Guidelines (C-GOOD-ERR) say an error type returned by a public function "should always implement the `std::error::Error` trait", and `anyhow::Error` cannot meet that. ## A review checklist - Does any public `fn` return `anyhow::Result`? Ask who matches on its errors. - Does any caller call `downcast_ref` on another crate's error? That is a hidden API contract, so move it into a typed variant. - Does generic code need `E: Error`? `anyhow::Error` will not satisfy it, so convert to a boxed `dyn Error` or keep the typed error.

  • Can a thiserror enum hold an `anyhow::Error` as its source, given that anyhow::Error is not `std::error::Error`?
    Yes. thiserror accepts any source type that implements `std::error::Error` or dereferences to `dyn std::error::Error`, and `anyhow::Error` derefs to `dyn Error + Send + Sync + 'static`. Its README shows `#[error(transparent)] Other(#[from] anyhow::Error)` as the catch-all variant: `Display` and `source()` are forwarded to the anyhow value.
  • How do you pass an `anyhow::Error` to an API that takes `Box<dyn std::error::Error + Send + Sync>`?
    Call `.into()` or use `?`. anyhow implements `From<anyhow::Error>` for `Box<dyn Error + Send + Sync + 'static>`, and also for the `Send`-only and plain boxed forms. The resulting box behaves as a normal `dyn Error`, so it satisfies APIs that want a boxed std error even though the original type does not implement the trait.
  • Why does the compiler not warn when the crate stops producing the type you downcast to?
    `downcast_ref::<E>()` accepts any `E: Display + Debug + Send + Sync + 'static` and compares type identities at run time. The signature `anyhow::Result<T>` says nothing about which types may be inside, so the compiler has nothing to check against. The call returns `None`, and the branch silently stops firing.

  • anyhow::Error implements std::error::Error, so it fits any E: Error bound.
  • If a downcast_ref compiles, it is guaranteed to match at run time.
  • anyhow in a library API is fine because callers can always downcast.
  • anyhow::Error cannot be turned into a Box<dyn Error + Send + Sync>.
  • The orphan rule is what stops anyhow::Error implementing std::error::Error.