Skip to content

Commit

Permalink
Remove 2 frames of noise from 'context' backtraces
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dtolnay committed Oct 20, 2022
1 parent f2123ab commit 131249b
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,23 @@ 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<C, F>(self, context: F) -> Result<T, Error>
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())),
}
}
}

Expand Down

0 comments on commit 131249b

Please sign in to comment.