Skip to content
Myr

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

5 files+223 added−51 removed

modified:src/context.rs+4 added-1 removed
100 unmodified lines
101 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}111112impl<C, E> Display for ContextError<C, E>
45 unmodified lines
modified:src/error.rs+9 added-46 removed
416 unmodified lines
417 self.inner.error_mut()418 }419}420421impl Debug for Error {421impl 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}426427impl Display for Error {428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {429 write!(f, "{}", self.inner.error())427impl Debug for Error {428 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {429 self.inner.debug(formatter)430 }431}432433unsafe impl Send for Error {}
217 unmodified lines
651 }652}653654impl 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 }658659 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 }662663 #[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.backtrace
1 unmodified line
670 .or_else(|| self.error().backtrace())671 .expect("backtrace capture failed")672 }673674 fn chain(&self) -> Chain {674 pub(crate) fn chain(&self) -> Chain {675 Chain {676 next: Some(self.error()),677 }678 }679680 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {681 writeln!(f, "{}", self.error())?;682683 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 }694695 #[cfg(backtrace)]696 {697 use std::backtrace::BacktraceStatus;698699 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 }713714 Ok(())715 }679}680681impl<E> StdError for ErrorImpl<E>682where
56 unmodified lines
added:src/fmt.rs+62 added
1use crate::error::ErrorImpl;2use std::fmt::{self, Debug};34impl ErrorImpl<()> {5 pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {6 write!(f, "{}", self.error())?;78 if f.alternate() {9 for cause in self.chain().skip(1) {10 write!(f, ": {}", cause)?;11 }12 }1314 Ok(())15 }1617 pub(crate) fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {18 if f.alternate() {19 return Debug::fmt(self.error(), f);20 }2122 writeln!(f, "{}", self.error())?;2324 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 }3536 #[cfg(backtrace)]37 {38 use std::backtrace::BacktraceStatus;3940 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 }5960 Ok(())61 }62}
modified:src/lib.rs+84 added
169 unmodified lines
170#[macro_use]171mod backtrace;172mod context;173mod error;174mod fmt;175mod kind;176mod macros;177178#[cfg(not(feature = "std"))]
15 unmodified lines
194/// - `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 &mdash; 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/// ```280pub struct Error {281 inner: ManuallyDrop<Box<ErrorImpl<()>>>,282}283
15 unmodified lines
299/// }300/// None301/// }302/// ```303#[derive(Clone)]304pub struct Chain<'a> {305 next: Option<&'a (dyn StdError + 'static)>,306}307
224 unmodified lines
modified:tests/test_fmt.rs+64 added-4 removed
1use anyhow::{bail, Context, Result};2use std::io;34fn f() -> Result<()> {4 bail!("oh no!");5 bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!"));6}78fn g() -> Result<()> {9 f().context("f failed")
2 unmodified lines
12fn h() -> Result<()> {13 g().context("g failed")14}1516const EXPECTED_ALTDISPLAY_F: &str = "\17oh no!\18";1920const EXPECTED_ALTDISPLAY_G: &str = "\21f failed: oh no!\22";2324const EXPECTED_ALTDISPLAY_H: &str = "\25g failed: f failed: oh no!\26";2728const EXPECTED_DEBUG_F: &str = "\29oh no!3018Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace31Stack backtrace:32 Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace33";3435const EXPECTED_DEBUG_G: &str = "\36f failed3738Caused by:39 oh no!4027Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace41Stack backtrace:42 Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace43";4445const EXPECTED_DEBUG_H: &str = "\46g failed
1 unmodified line
48Caused by:49 0: f failed50 1: oh no!5137Backtrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace52Stack backtrace:53 Run with RUST_LIB_BACKTRACE=1 env variable to display a backtrace54";5556const EXPECTED_ALTDEBUG_F: &str = "\57Custom {58 kind: PermissionDenied,59 error: \"oh no!\",60}\61";6263const EXPECTED_ALTDEBUG_G: &str = "\64Error {65 context: \"f failed\",66 source: Custom {67 kind: PermissionDenied,68 error: \"oh no!\",69 },70}\71";7273const EXPECTED_ALTDEBUG_H: &str = "\74Error {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";8586#[test]87fn test_display() {88 assert_eq!("g failed", h().unwrap_err().to_string());89}9091#[test]92fn 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}9798#[test]99#[cfg_attr(not(backtrace), ignore)]100fn 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}105106#[test]107fn 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}