Home-made back trace (stack trace) solution, given that backtrace fails to work? Is my proposal feasible, good or bad?

Hi, I find backtrace does not produce frames of my code after a lot of attempts in Android. Therefore, I want to make a home-made backtrace as follows.

Instead of using ? or try!, I will create a macro called my_try! as follows:

macro_rules! my_try {
    ($expr:expr $(,)?) => {
        match $expr {
            $crate::result::Result::Ok(val) => val,
            $crate::result::Result::Err(err) => {
                return $crate::result::Result::Err(err.context($generate_a_number));

where err is of type anyhow::Error, and .context($generate_a_number) means that, I will attach a unique number to this error when it is returned from this location. For example, a my_try! usage at file a.rs line 42 may be tied to number 123456, and I output a mapping saying that "123456 means a.rs@line42".

By using this approach, even though the backtrace does not produce what I want, I can still get (pseudo) stack traces. For example, if I finally see an error with context [123456, 234567, ...], then I know this error comes from a.rs@line42, followed by b.rs@line123, etc.

Question: Is this a good/feasible approach? Will I face problems? Does this solution already exist or I have to invent the wheel?

Thanks for any suggestions!

Check out file!, line! and column!

Thanks. I know I will use some macros; the question is, will this approach be good or bad?

I mean, it would be best to get the built in backtraces to work, but if you can't, it seems like a fine workaround.

1 Like

What about creating an extension trait like anyhow::Context which wraps an error and uses #[track_caller] to record which line invoked the extension trait's method?

1 Like

Thanks for your replies! Indeed I have made backtrace to work (after some efforts of attempts though).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.