Skip to content

Commit 131249b

Browse files
committed
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: <E as anyhow::context::ext::StdError>::ext_context at /git/anyhow/src/context.rs:27:29 1: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::context::{{closure}} at /git/anyhow/src/context.rs:50:30 2: core::result::Result<T,E>::map_err at /rustc/4b8f4319954ff2642690b9e5cbe4af352d095bf6/library/core/src/result.rs:861:27 3: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::context at /git/anyhow/src/context.rs:50:9 4: testing::main at ./src/main.rs:5:5 After: 0: <E as anyhow::context::ext::StdError>::ext_context at /git/anyhow/src/context.rs:27:29 1: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::context at /git/anyhow/src/context.rs:52:31 2: testing::main at ./src/main.rs:5:5
1 parent f2123ab commit 131249b

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/context.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,23 @@ where
4747
where
4848
C: Display + Send + Sync + 'static,
4949
{
50-
self.map_err(|error| error.ext_context(context))
50+
// Not using map_err to save 2 useless frames off the captured backtrace
51+
// in ext_context.
52+
match self {
53+
Ok(ok) => Ok(ok),
54+
Err(error) => Err(error.ext_context(context)),
55+
}
5156
}
5257

5358
fn with_context<C, F>(self, context: F) -> Result<T, Error>
5459
where
5560
C: Display + Send + Sync + 'static,
5661
F: FnOnce() -> C,
5762
{
58-
self.map_err(|error| error.ext_context(context()))
63+
match self {
64+
Ok(ok) => Ok(ok),
65+
Err(error) => Err(error.ext_context(context())),
66+
}
5967
}
6068
}
6169

0 commit comments

Comments
 (0)