Merge pull request #42 from dtolnay/fmt
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add and document {:#} and {:#?} alt format representations
authored by David Tolnay · committed by GitHub · parents 04b11c5, c30a32b · Browse files · 5 files·+223 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+223 added−51 removed
- tests:+64 added−4 removed
- other:+159 added−47 removed
Provenance
- Commit
74954bd- Tree
1639b41- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
04b11c5- Parent 2
c30a32b
5 files changed+223 added−51 removed
modified:src/context.rs+4 added-1 removed
100 unmodified lines101 C: Display,102 E: Debug,103 {104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {105- write!(f, "{}\nCaused by: {:?}", self.context, self.error)105+ f.debug_struct("Error")106+ .field("context", &self.context.to_string())107+ .field("source", &self.error)108+ .finish()109 }110 }111 112 impl<C, E> Display for ContextError<C, E>45 unmodified linesmodified:src/error.rs+9 added-46 removed
416 unmodified lines417 self.inner.error_mut()418 }419 }420 421-impl Debug for Error {421+impl Display for Error {422 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {423- self.inner.debug(formatter)423+ self.inner.display(formatter)424 }425 }426 427-impl Display for Error {428- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {429- write!(f, "{}", self.inner.error())427+impl Debug for Error {428+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {429+ self.inner.debug(formatter)430 }431 }432 433 unsafe impl Send for Error {}217 unmodified lines651 }652 }653 654 impl ErrorImpl<()> {655- fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {655+ pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {656 unsafe { &*(self.vtable.object_ref)(self) }657 }658 659- fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {659+ pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {660 unsafe { &mut *(self.vtable.object_mut)(self) }661 }662 663 #[cfg(backtrace)]664- fn backtrace(&self) -> &Backtrace {664+ pub(crate) fn backtrace(&self) -> &Backtrace {665 // This unwrap can only panic if the underlying error's backtrace method666 // is nondeterministic, which would only happen in maliciously667 // constructed code.668 self.backtrace1 unmodified line670 .or_else(|| self.error().backtrace())671 .expect("backtrace capture failed")672 }673 674- fn chain(&self) -> Chain {674+ pub(crate) fn chain(&self) -> Chain {675 Chain {676 next: Some(self.error()),677 }678 }679-680- fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {681- writeln!(f, "{}", self.error())?;682-683- let mut chain = self.chain().skip(1).enumerate().peekable();684- if let Some((n, error)) = chain.next() {685- write!(f, "\nCaused by:\n ")?;686- if chain.peek().is_some() {687- write!(f, "{}: ", n)?;688- }689- writeln!(f, "{}", error)?;690- for (n, error) in chain {691- writeln!(f, " {}: {}", n, error)?;692- }693- }694-695- #[cfg(backtrace)]696- {697- use std::backtrace::BacktraceStatus;698-699- let backtrace = self.backtrace();700- match backtrace.status() {701- BacktraceStatus::Captured => {702- writeln!(f, "\n{}", backtrace)?;703- }704- BacktraceStatus::Disabled => {705- writeln!(706- f,707- "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"708- )?;709- }710- _ => {}711- }712- }713-714- Ok(())715- }679 }680 681 impl<E> StdError for ErrorImpl<E>682 where56 unmodified linesadded:src/fmt.rs+62 added
1+use crate::error::ErrorImpl;2+use std::fmt::{self, Debug};3+4+impl ErrorImpl<()> {5+ pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {6+ write!(f, "{}", self.error())?;7+8+ if f.alternate() {9+ for cause in self.chain().skip(1) {10+ write!(f, ": {}", cause)?;11+ }12+ }13+14+ Ok(())15+ }16+17+ pub(crate) fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {18+ if f.alternate() {19+ return Debug::fmt(self.error(), f);20+ }21+22+ writeln!(f, "{}", self.error())?;23+24+ let mut chain = self.chain().skip(1).enumerate().peekable();25+ if let Some((n, error)) = chain.next() {26+ write!(f, "\nCaused by:\n ")?;27+ if chain.peek().is_some() {28+ write!(f, "{}: ", n)?;29+ }30+ writeln!(f, "{}", error)?;31+ for (n, error) in chain {32+ writeln!(f, " {}: {}", n, error)?;33+ }34+ }35+36+ #[cfg(backtrace)]37+ {38+ use std::backtrace::BacktraceStatus;39+40+ let backtrace = self.backtrace();41+ match backtrace.status() {42+ BacktraceStatus::Captured => {43+ let mut backtrace = backtrace.to_string();44+ if backtrace.starts_with("stack backtrace:") {45+ // Capitalize to match "Caused by:"46+ backtrace.replace_range(0..1, "S");47+ }48+ write!(f, "\n{}", backtrace)?;49+ }50+ BacktraceStatus::Disabled => {51+ writeln!(52+ f,53+ "\nStack backtrace:\n Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace"54+ )?;55+ }56+ _ => {}57+ }58+ }59+60+ Ok(())61+ }62+}modified:src/lib.rs+84 added
169 unmodified lines170 #[macro_use]171 mod backtrace;172 mod context;173 mod error;174+mod fmt;175 mod kind;176 mod macros;177 178 #[cfg(not(feature = "std"))]15 unmodified lines194 /// - `Error` guarantees that a backtrace is available, even if the underlying195 /// error type does not provide one.196 /// - `Error` is represented as a narrow pointer — exactly one word in197 /// size instead of two.198+///199+/// <br>200+///201+/// # Display representations202+///203+/// When you print an error object using "{}" or to_string(), only the outermost204+/// underlying error or context is printed, not any of the lower level causes.205+/// This is exactly as if you had called the Display impl of the error from206+/// which you constructed your anyhow::Error.207+///208+/// ```console209+/// failed to read instrs from ./path/to/instrs.jsox210+/// ```211+///212+/// To print causes as well using anyhow's default formatting of causes, use the213+/// alternate selector "{:#}".214+///215+/// ```console216+/// failed to read instrs from ./path/to/instrs.jsox: No such file or directory (os error 2)217+/// ```218+///219+/// The Debug format "{:?}" includes your backtrace if one was captured. Note220+/// that this is the representation you get by default if you return an error221+/// from `fn main` instead of printing it explicitly yourself.222+///223+/// ```console224+/// Error: failed to read instrs from ./path/to/instrs.jsox225+///226+/// Caused by:227+/// No such file or directory (os error 2)228+///229+/// Stack backtrace:230+/// 0: <E as anyhow::context::ext::StdError>::ext_context231+/// at /git/anyhow/src/backtrace.rs:26232+/// 1: core::result::Result<T,E>::map_err233+/// at /git/rustc/src/libcore/result.rs:596234+/// 2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context235+/// at /git/anyhow/src/context.rs:58236+/// 3: testing::main237+/// at src/main.rs:5238+/// 4: std::rt::lang_start239+/// at /git/rustc/src/libstd/rt.rs:61240+/// 5: main241+/// 6: __libc_start_main242+/// 7: _start243+/// ```244+///245+/// To see a conventional struct-style Debug representation, use "{:#?}".246+///247+/// ```console248+/// Error {249+/// context: "failed to read instrs from ./path/to/instrs.jsox",250+/// source: Os {251+/// code: 2,252+/// kind: NotFound,253+/// message: "No such file or directory",254+/// },255+/// }256+/// ```257+///258+/// If none of the built-in representations are appropriate and you would prefer259+/// to render the error and its cause chain yourself, it can be done something260+/// like this:261+///262+/// ```263+/// use anyhow::{Context, Result};264+///265+/// fn main() {266+/// if let Err(err) = try_main() {267+/// eprintln!("ERROR: {}", err);268+/// err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));269+/// std::process::exit(1);270+/// }271+/// }272+///273+/// fn try_main() -> Result<()> {274+/// # const IGNORE: &str = stringify! {275+/// ...276+/// # };277+/// # Ok(())278+/// }279+/// ```280 pub struct Error {281 inner: ManuallyDrop<Box<ErrorImpl<()>>>,282 }283 15 unmodified lines299 /// }300 /// None301 /// }302 /// ```303+#[derive(Clone)]304 pub struct Chain<'a> {305 next: Option<&'a (dyn StdError + 'static)>,306 }307 224 unmodified linesmodified:tests/test_fmt.rs+64 added-4 removed
1 use anyhow::{bail, Context, Result};2+use std::io;3 4 fn f() -> Result<()> {4- bail!("oh no!");5+ bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));6 }7 8 fn g() -> Result<()> {9 f().context("f failed")2 unmodified lines12 fn h() -> Result<()> {13 g().context("g failed")14 }15 16+const EXPECTED_ALTDISPLAY_F: &str = "\17+oh no!\18+";19+20+const EXPECTED_ALTDISPLAY_G: &str = "\21+f failed: oh no!\22+";23+24+const EXPECTED_ALTDISPLAY_H: &str = "\25+g failed: f failed: oh no!\26+";27+28 const EXPECTED_DEBUG_F: &str = "\29 oh no!30 18-Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace31+Stack backtrace:32+ Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace33 ";34 35 const EXPECTED_DEBUG_G: &str = "\36 f failed37 38 Caused by:39 oh no!40 27-Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace41+Stack backtrace:42+ Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace43 ";44 45 const EXPECTED_DEBUG_H: &str = "\46 g failed1 unmodified line48 Caused by:49 0: f failed50 1: oh no!51 37-Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace52+Stack backtrace:53+ Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace54 ";55 56+const EXPECTED_ALTDEBUG_F: &str = "\57+Custom {58+ kind: PermissionDenied,59+ error: \"oh no!\",60+}\61+";62+63+const EXPECTED_ALTDEBUG_G: &str = "\64+Error {65+ context: \"f failed\",66+ source: Custom {67+ kind: PermissionDenied,68+ error: \"oh no!\",69+ },70+}\71+";72+73+const EXPECTED_ALTDEBUG_H: &str = "\74+Error {75+ context: \"g failed\",76+ source: Error {77+ context: \"f failed\",78+ source: Custom {79+ kind: PermissionDenied,80+ error: \"oh no!\",81+ },82+ },83+}\84+";85+86 #[test]87 fn test_display() {88 assert_eq!("g failed", h().unwrap_err().to_string());89 }90 91 #[test]92+fn test_altdisplay() {93+ assert_eq!(EXPECTED_ALTDISPLAY_F, format!("{:#}", f().unwrap_err()));94+ assert_eq!(EXPECTED_ALTDISPLAY_G, format!("{:#}", g().unwrap_err()));95+ assert_eq!(EXPECTED_ALTDISPLAY_H, format!("{:#}", h().unwrap_err()));96+}97+98+#[test]99 #[cfg_attr(not(backtrace), ignore)]100 fn test_debug() {101 assert_eq!(EXPECTED_DEBUG_F, format!("{:?}", f().unwrap_err()));102 assert_eq!(EXPECTED_DEBUG_G, format!("{:?}", g().unwrap_err()));103 assert_eq!(EXPECTED_DEBUG_H, format!("{:?}", h().unwrap_err()));104 }105+106+#[test]107+fn test_altdebug() {108+ assert_eq!(EXPECTED_ALTDEBUG_F, format!("{:#?}", f().unwrap_err()));109+ assert_eq!(EXPECTED_ALTDEBUG_G, format!("{:#?}", g().unwrap_err()));110+ assert_eq!(EXPECTED_ALTDEBUG_H, format!("{:#?}", h().unwrap_err()));111+}