From 131249b11c0facb18d0aa5a6c677c1b9da08ef66 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 20 Oct 2022 14:25:46 -0700 Subject: [PATCH] Remove 2 frames of noise from 'context' backtraces Repro: use anyhow::Context; fn main() -> anyhow::Result<()> { let result = Err(std::fmt::Error); result.context("...") } Before: 0: ::ext_context at /git/anyhow/src/context.rs:27:29 1: anyhow::context:: for core::result::Result>::context::{{closure}} at /git/anyhow/src/context.rs:50:30 2: core::result::Result::map_err at /rustc/4b8f4319954ff2642690b9e5cbe4af352d095bf6/library/core/src/result.rs:861:27 3: anyhow::context:: for core::result::Result>::context at /git/anyhow/src/context.rs:50:9 4: testing::main at ./src/main.rs:5:5 After: 0: ::ext_context at /git/anyhow/src/context.rs:27:29 1: anyhow::context:: for core::result::Result>::context at /git/anyhow/src/context.rs:52:31 2: testing::main at ./src/main.rs:5:5 --- src/context.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/context.rs b/src/context.rs index 1b7dd31..238473e 100644 --- a/src/context.rs +++ b/src/context.rs @@ -47,7 +47,12 @@ where where C: Display + Send + Sync + 'static, { - self.map_err(|error| error.ext_context(context)) + // Not using map_err to save 2 useless frames off the captured backtrace + // in ext_context. + match self { + Ok(ok) => Ok(ok), + Err(error) => Err(error.ext_context(context)), + } } fn with_context(self, context: F) -> Result @@ -55,7 +60,10 @@ where C: Display + Send + Sync + 'static, F: FnOnce() -> C, { - self.map_err(|error| error.ext_context(context())) + match self { + Ok(ok) => Ok(ok), + Err(error) => Err(error.ext_context(context())), + } } }