error-concept

anyhow: recover a concrete error type

Inspect a known underlying error by type, even after adding context. A mismatched type yields None from downcast_ref. Requires anyhow = "=1.0.104" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): parse=true Expected stderr: (empty) Expected exit: success Common mistake: Branching on the wording of a diagnostic or assuming every error has the type you expect.

Formal Syntax & Structure

rust syntaxrust
error.downcast_ref::<E>(); error.is::<E>()

Working Example

Example Snippetrust
use anyhow::Context;use std::num::ParseIntError;fn main() {    if let Err(e) = "bad".parse::<u32>().context("count") {        println!("parse={}", e.downcast_ref::<ParseIntError>().is_some());    }}
Rust Reference