Skip to content

Commit

Permalink
Rewrite top-level Reporting doc section
Browse files Browse the repository at this point in the history
- start by explaining that printing an error will only display the top-level message
- change example to include a source error,
  and show the differences between outputs
  • Loading branch information
Enet4 committed Nov 1, 2024
1 parent 2c59206 commit 4311efb
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,31 +203,61 @@
//!
//! ## Reporting
//!
//! SNAFU also offers a user-friendly error output mechanism,
//! available through the [`macro@report`] procedural macro
//! or using the [`Report`] type directly.
//! Printing an error via [`Display`][]
//! will only show the top-level error message without the underlying sources.
//! For an extended error report,
//! SNAFU offers a user-friendly error output mechanism.
//! It prints the main error and all underlying errors in the chain,
//! from the most recent to the oldest,
//! plus the [backtrace](Backtrace) if applicable.
//! This is done by using the [`macro@report`] procedural macro
//! or the [`Report`] type directly.
//!
//! ```no_run
//! use snafu::prelude::*;
//!
//! #[derive(Debug, Snafu)]
//! enum Error {
//! #[snafu(display("Bad ID, was {id}"))]
//! InvalidId { id: u16 },
//! #[snafu(display("Could not load configuration file {path}"))]
//! struct ConfigFileError {
//! source: std::io::Error,
//! path: String,
//! }
//!
//! fn is_valid_id(id: u16) -> Result<(), Error> {
//! ensure!(id >= 10, InvalidIdSnafu { id });
//! Ok(())
//! fn read_config_file(path: &str) -> Result<String, ConfigFileError> {
//! std::fs::read_to_string(path).context(ConfigFileSnafu { path })
//! }
//!
//! #[snafu::report]
//! fn main() -> Result<(), Error> {
//! is_valid_id(5)?;
//! fn main() -> Result<(), ConfigFileError> {
//! read_config_file("bad-config.ini")?;
//! Ok(())
//! }
//! ```
//!
//! This will print:
//!
//! ```none
//! Error: Could not load configuration file bad-config.ini
//!
//! Caused by this error:
//! 1: No such file or directory (os error 2)
//! ```
//!
//! Which shows the underlying errors, unlike [`Display`]:
//!
//! ```none
//! Error: Could not load configuration file bad-config.ini
//! ```
//!
//! ... and is also more readable than the [`Debug`] output:
//!
//! ```none
//! Error: ConfigFileError { source: Os { code: 2, kind: NotFound, message: "No such file or directory" }, path: "bad-config.ini" }
//! ```
//!
//! [`Display`]: core::fmt::Display
//! [`Debug`]: core::fmt::Debug
//!
//! ## Next steps
//!
//! Read the documentation for the [`Snafu`][] macro to see all of the
Expand Down

0 comments on commit 4311efb

Please sign in to comment.