anyhow icon indicating copy to clipboard operation
anyhow copied to clipboard

Debug representation of anyhow::Error does not use Debug representation of underlying error

Open JK-WP opened this issue 3 years ago • 0 comments

Apologies if I am misunderstanding horribly, but anyhow::Error appears to violate the understanding that {:?} should use the Debug representation, and instead uses the Display representation of the inner error, which I think is because of line #26 in anyhow/src/fmt.rs. A simple repro is as follows:

#[derive(Debug)]
struct MyError { details: String }

impl std::fmt::Display for MyError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "MyError") }
}

impl std::error::Error for MyError {}

//==============================================================================

fn bad_request() -> Result<(), MyError> {
  Err(MyError{details: "important info".to_owned()})
}

fn make_bad_request() -> anyhow::Result<()> {
  bad_request().map_err(|e| { eprintln!("In make_bad_request: ->|{e:?}|<-"); e })?;
  Ok(())
}

fn main() {
  make_bad_request().map_err(|e| { eprintln!("In main: ->|{e:?}|<-"); e }).unwrap();
}

which produces:

In make_bad_request: ->|MyError { details: "important info" }|<-
In main: ->|MyError|<-
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: MyError'

It feels counterintuitive that wrapping the inner error in anyhow::Error should change its fundamental display behaviour, including what is displayed in case of a panic.

Changing the formatting to {:#?} does result in the Debug representation of the inner error being used, but that doesn't feel like the correct usage of the 'alternate' flag, which I think is more conventionally used for things such as pretty printing.

JK-WP avatar Jun 07 '22 06:06 JK-WP