From 3041dcb4963261bcfac9add24976d3aeafe83b9c Mon Sep 17 00:00:00 2001 From: Arpad Borsos Date: Thu, 17 Jun 2021 10:00:11 +0200 Subject: [PATCH] fix: Work around anyhow::msg not having a proper Debug::fmt The generic `anyhow::msg` will just `Debug::fmt` the `String` that you feed it, which results in Error types with leading quotes. --- sentry-core/src/error.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/sentry-core/src/error.rs b/sentry-core/src/error.rs index 4ee16db1d..0a96538dc 100644 --- a/sentry-core/src/error.rs +++ b/sentry-core/src/error.rs @@ -98,8 +98,21 @@ pub fn event_from_error(err: &E) -> Event<'static> { fn exception_from_error(err: &E) -> Exception { let dbg = format!("{:?}", err); + let value = err.to_string(); + + // A generic `anyhow::msg` will just `Debug::fmt` the `String` that you feed + // it. Trying to parse the type name from that will result in a leading quote + // and the first word, so quite useless. + // To work around this, we check if the `Debug::fmt` of the complete error + // matches its `Display::fmt`, in which case there is no type to parse and + // we will just be using `Error`. + let ty = if dbg == format!("{:?}", value) { + String::from("Error") + } else { + parse_type_from_debug(&dbg).to_owned() + }; Exception { - ty: parse_type_from_debug(&dbg).to_owned(), + ty, value: Some(err.to_string()), ..Default::default() } @@ -146,3 +159,14 @@ fn test_parse_type_from_debug() { ); assert_eq!(parse(&err), "ParseIntError"); } + +#[test] +fn test_parse_anyhow_as_error() { + let anyhow_err = anyhow::anyhow!("Ooops, something bad happened"); + let err: &dyn Error = anyhow_err.as_ref(); + + let exc = exception_from_error(err); + + assert_eq!(&exc.ty, "Error"); + assert_eq!(exc.value.as_deref(), Some("Ooops, something bad happened")); +}