Always had the problem that if I wanted to just log an error, rather than bubble it all the way up to main(), that you wouldn’t get a stacktrace. You could iterate the source chain and plug the stacktrace together yourself, but it’s rather complex code.

Now I realized, you can do this to get a stacktrace:

let error = todo!("Get an error somehow...");
let error = anyhow::anyhow!(error); //converts to an `anyhow::Error`
eprintln!("Error with stacktrace: {error:?}");

For converting to an anyhow::Error, it often also makes sense to use anyhow::Context like so:

use anyhow::Context;
let error = error.context("Deleting file failed.");
  • TehPers@beehaw.org
    link
    fedilink
    English
    arrow-up
    2
    ·
    1 day ago

    The error returns a stack trace like this because if you return Err(anyhow::Error) from your main function, it debug prints the error when it exits.

    As you mentioned, it’s very convenient during logging! The Display impl shows much less information, so usually you want the Debug info of anyhow::Error during logging.