CodeSampleX

Пример

anyhow 1.0.104: 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

Проверенный пример — cargo anyhow 1.0.104: Handle errors in a Rust application with anyhow: attach context, keep the cause chain, log it without losing the…

sha256:709971847660bb4f230ee832aa66da4263481bd8d5e0a498178ee3b789c53404

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда rust 1 linux x64 rust 1 rust cargo

Среды запусков проверки

Окружение Контракт Этапы Запуск
rust 1 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-14
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
Цель
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
Пакеты
Символы
  • anyhow::Context::context
  • anyhow::Context::with_context
  • anyhow::Error::chain
  • anyhow::Error::root_cause
  • anyhow::Error::downcast_ref
  • anyhow::bail
  • anyhow::ensure
Окружение
rust 1
Создан
2026-08-14T08:53:52Z

Контракт

  1. assert the bare io::Error for a missing path is NotFound and its Display carries os error 2
  2. assert Display of a context-wrapped error prints only the outermost context, not the io message
  3. assert alternate Display {:#} flattens the whole chain into one colon-joined line while {} does not
  4. assert chain() yields both context frames then the original io error, in that order
  5. assert root_cause() returns the original io error at the bottom of the chain
  6. assert Debug {:?} prints the multi-line report with a Caused by section
  7. assert anyhow::Error derefs to a dyn StdError that prints as the outermost frame, and that source() through that Deref yields the next frame
  8. assert downcast_ref recovers the io::Error and its NotFound kind through two layers of context
  9. assert downcast_ref recovers a concrete thiserror library type out of a context-wrapped anyhow error
  10. assert anyhow::Error is one pointer wide, smaller than the concrete thiserror error, which is as wide as its String field
  11. assert bail! and ensure! build a one-frame error from a plain message with no source
  12. assert an interpolated bail! message downcasts to String while an anyhow! bare literal downcasts to &str
  13. assert io::Error and ParseIntError both convert through ? with no From impl written
  14. assert context() on a None Option produces an error with no source
  15. assert with_context never runs its closure on the success path while context() builds its message even when the Result is Ok

Файлы

  • Cargo.lock
  • Cargo.toml
  • csx.json
  • src/main.rs

Скачать артефакт с исходным кодом (tar.gz)

Исходный сидер

anonymous