샘플
anyhow 1.0.104: Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions
검증된 샘플 — cargo anyhow 1.0.104: Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object…
sha256:111c5fe00d1de4f527fc0ae3c444b12d048965ac957370eb4630a2a4a08b239f
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
rust linux x64 rust rust cargo
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-16 |
| rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · cargo@1 |
2026-08-18 |
케이스
HOW- 목표
- Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions
- 패키지
- 심벌
-
- anyhow::Error::downcast_ref
- anyhow::Error::downcast_mut
- anyhow::Error::downcast
- anyhow::Error::from_boxed
- anyhow::Error::is
- anyhow::Context::context
- 환경
- rust
- 생성일
- 2026-08-16T07:54:47Z
컨트랙트
- assert converting Box<dyn StdError> via from_boxed prevents recovering the concrete error with downcast_ref because TypeId tracks the boxed trait object
- assert converting a concrete StdError via From/into enables downcast_ref and is::<E>
- assert anyhow::Error::downcast_ref recursively searches through all attached context frames to find the root error
- assert std::error::Error::downcast_ref called via Deref on &dyn StdError fails on context-wrapped errors because std downcast does not traverse causes
- assert downcast_ref recovers custom context structs implementing Display and Debug even if they do not implement std::error::Error
- assert downcast_ref and downcast_mut on duplicate context types target the outermost most recently attached context frame
- assert downcast by value extracts the root error out of context layers, while mismatched downcast preserves the entire context chain intact
- assert context on Option None creates a root error with source None, whereas context on Result Err chains the previous error as source
파일
- Cargo.lock
- Cargo.toml
- NOTES.md
- csx.json
- src/lib.rs
소스
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "cargo-anyhow-api"
version = "0.1.0"
dependencies = [
"anyhow",
]
[package]
name = "cargo-anyhow-api"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.104"
# Notes
## Prior Sample Found
`search_known_solution` returned existing published sample `sha256:709971847660bb4f230ee832aa66da4263481bd8d5e0a498178ee3b789c53404` ("Handle errors in a Rust application with anyhow: attach context, keep the cause chain, log it without losing the cause, and recover the concrete error"), which focused on `{}` vs `{:#}` Display formatting loss, `chain()` iteration order, and basic `thiserror` downcasting.
## What a Model Would Have Written Instead
A competent model would assume `anyhow::Error::from_boxed(boxed_dyn_err).downcast_ref::<ConcreteError>()` recovers the concrete error from boxed trait objects returned by external libraries, and that calling `downcast_ref::<ConcreteError>()` on `&dyn std::error::Error` (via `anyhow::Error`'s `Deref` coercion) searches the cause chain just like `anyhow::Error::downcast_ref`.
## How the Wrong Version Fails
Silently at runtime: `downcast_ref::<ConcreteError>()` returns `None` without any compile warning or panic, silently disabling error recovery branches and fallback handling while passing compilation.
{"case":{"caseId":"case:sha256:364d3ddc0312b1f6ceff0b194764a1226e2700090a99d6b9afe439c61a559717","contract":["assert converting Box\u003cdyn StdError\u003e via from_boxed prevents recovering the concrete error with downcast_ref because TypeId tracks the boxed trait object","assert converting a concrete StdError via From/into enables downcast_ref and is::\u003cE\u003e","assert anyhow::Error::downcast_ref recursively searches through all attached context frames to find the root error","assert std::error::Error::downcast_ref called via Deref on \u0026dyn StdError fails on context-wrapped errors because std downcast does not traverse causes","assert downcast_ref recovers custom context structs implementing Display and Debug even if they do not implement std::error::Error","assert downcast_ref and downcast_mut on duplicate context types target the outermost most recently attached context frame","assert downcast by value extracts the root error out of context layers, while mismatched downcast preserves the entire context chain intact","assert context on Option None creates a root error with source None, whereas context on Result Err chains the previous error as source"],"goal":"Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions","kind":"HOW","packages":["pkg:cargo/anyhow@1.0.104"],"schemaVersion":1,"symbols":["anyhow::Error::downcast_ref","anyhow::Error::downcast_mut","anyhow::Error::downcast","anyhow::Error::from_boxed","anyhow::Error::is","anyhow::Context::context"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/anyhow@1.0.104"],"schemaVersion":1,"symbols":["anyhow::Error::downcast_ref","anyhow::Error::downcast_mut","anyhow::Error::downcast","anyhow::Error::from_boxed","anyhow::Error::is","anyhow::Context::context"],"verifierAdapter":"cargo@1"}
use std::error::Error as StdError;
use std::fmt;
use anyhow::{Context, Result};
/// Concrete error type implementing `std::error::Error`.
#[derive(Debug, PartialEq, Eq)]
pub struct QueryError {
pub query_id: u64,
pub reason: &'static str,
}
impl fmt::Display for QueryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "query {} failed: {}", self.query_id, self.reason)
}
}
impl StdError for QueryError {}
/// Custom metadata / diagnostic context that implements `Display` and `Debug`
/// but deliberately DOES NOT implement `std::error::Error`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceMetadata {
pub trace_id: &'static str,
pub attempt: u32,
}
impl fmt::Display for TraceMetadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "trace_id={}, attempt={}", self.trace_id, self.attempt)
}
}
/// Demonstrates how anyhow interacts with standard trait objects,
/// nested context chains, and downcasting semantics.
pub fn execute_query(id: u64) -> Result<String> {
if id == 0 {
return Err(QueryError {
query_id: 0,
reason: "invalid query id",
})
.context("validating query input")
.context("dispatching execution");
}
Ok(format!("result for {id}"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
#[test]
fn test_from_boxed_vs_direct_into_downcast_trap() {
// TRAP 1: When receiving Box<dyn StdError + Send + Sync + 'static> (e.g. from generic crates),
// callers use anyhow::Error::from_boxed. But from_boxed wraps the trait object itself.
// Calling downcast_ref::<QueryError>() SILENTLY returns None because the internal TypeId
// is for Box<dyn StdError + Send + Sync>, not QueryError.
let concrete = QueryError {
query_id: 42,
reason: "connection reset",
};
let boxed: Box<dyn StdError + Send + Sync + 'static> = Box::new(concrete);
let err_from_boxed = anyhow::Error::from_boxed(boxed);
// A naive caller expects to recover QueryError from the anyhow::Error, but it fails:
assert!(!err_from_boxed.is::<QueryError>());
assert!(err_from_boxed.downcast_ref::<QueryError>().is_none());
// In contrast, direct conversion via From/into preserves the concrete TypeId:
let err_from_concrete: anyhow::Error = QueryError {
query_id: 42,
reason: "connection reset",
}
.into();
assert!(err_from_concrete.is::<QueryError>());
assert_eq!(
err_from_concrete.downcast_ref::<QueryError>(),
Some(&QueryError {
query_id: 42,
reason: "connection reset"
})
);
}
#[test]
fn test_anyhow_downcast_traversal_vs_stderror_deref_downcast() {
// TRAP 2: anyhow::Error::downcast_ref traverses the entire cause chain through attached contexts.
// However, anyhow::Error implements Deref<Target = dyn StdError + Send + Sync + 'static>.
// When passed to functions taking &dyn StdError, calling std::error::Error::downcast_ref
// checks ONLY the outermost context frame and does NOT traverse causes.
let err = execute_query(0).unwrap_err();
// anyhow::Error::downcast_ref traverses context layers and successfully finds the root QueryError:
let found_anyhow = err.downcast_ref::<QueryError>();
assert_eq!(
found_anyhow,
Some(&QueryError {
query_id: 0,
reason: "invalid query id"
})
);
// std::error::Error::downcast_ref via Deref looks ONLY at the outer context frame and returns None:
let std_dyn: &(dyn StdError + 'static) = &*err;
let found_std = std_dyn.downcast_ref::<QueryError>();
assert!(found_std.is_none());
}
#[test]
fn test_non_error_context_payload_downcast_and_precedence() {
// TRAP 3: Context attached via .context(C) only requires C: Display + Debug + Send + Sync + 'static.
// It does NOT require std::error::Error, and custom context structs CAN be downcasted.
// When multiple contexts of the same type are chained, downcast_ref and downcast_mut resolve
// to the OUTERMOST (most recently attached) frame, not the first one.
let base_err = QueryError {
query_id: 10,
reason: "timeout",
};
let mut err = anyhow::Error::from(base_err)
.context(TraceMetadata {
trace_id: "inner-trace",
attempt: 1,
})
.context(TraceMetadata {
trace_id: "outer-trace",
attempt: 2,
});
// downcast_ref returns the outermost context frame:
assert_eq!(
err.downcast_ref::<TraceMetadata>(),
Some(&TraceMetadata {
trace_id: "outer-trace",
attempt: 2,
})
);
// downcast_mut modifies the outermost matching context frame in place:
if let Some(meta) = err.downcast_mut::<TraceMetadata>() {
meta.attempt = 3;
}
assert_eq!(
err.downcast_ref::<TraceMetadata>(),
Some(&TraceMetadata {
trace_id: "outer-trace",
attempt: 3,
})
);
// Root error is still accessible despite multiple non-error context layers:
assert_eq!(
err.downcast_ref::<QueryError>(),
Some(&QueryError {
query_id: 10,
reason: "timeout"
})
);
}
#[test]
fn test_downcast_by_value_extracts_root_and_preserves_on_mismatch() {
// TRAP 4: err.downcast::<E>() extracts the root error by value, consuming all context wrappers.
// If the downcast fails (mismatched type), the returned Err variant retains the FULL original
// error with all context frames intact.
let err = execute_query(0).unwrap_err();
// Failed downcast returns the full error intact:
let mismatch_res = err.downcast::<io::Error>();
assert!(mismatch_res.is_err());
let preserved_err = mismatch_res.unwrap_err();
assert_eq!(preserved_err.chain().count(), 3);
assert_eq!(preserved_err.to_string(), "dispatching execution");
// Successful downcast unwraps the root error:
let success_res = preserved_err.downcast::<QueryError>();
assert!(success_res.is_ok());
let root = success_res.unwrap();
assert_eq!(
root,
QueryError {
query_id: 0,
reason: "invalid query id"
}
);
}
#[test]
fn test_option_context_source_asymmetry() {
// TRAP 5: Context on Option<T>::None creates a standalone error with no underlying cause.
// err.source() is None and chain().count() is 1.
// In contrast, Context on Result::Err(E) wraps the error, making source() Some(E) and chain().count() 2.
let opt: Option<u64> = None;
let opt_err = opt.context("missing config key").unwrap_err();
assert!(opt_err.source().is_none());
assert_eq!(opt_err.chain().count(), 1);
assert_eq!(opt_err.to_string(), "missing config key");
let res: std::result::Result<u64, QueryError> = Err(QueryError {
query_id: 1,
reason: "aborted",
});
let res_err = res.context("missing config key").unwrap_err();
assert!(res_err.source().is_some());
assert_eq!(res_err.chain().count(), 2);
assert_eq!(res_err.to_string(), "missing config key");
assert_eq!(
res_err.source().unwrap().to_string(),
"query 1 failed: aborted"
);
}
}