17
submitted 1 day ago by Ephera@lemmy.ml to c/rust@lemmy.ml

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.");
you are viewing a single comment's thread
view the rest of the comments
[-] Ephera@lemmy.ml 3 points 1 day ago

Other useful Debug implementations:

  • PathBuf and Path will give you the path with quotes and I believe, it escapes any non-UTF8 characters.
  • std::time::Duration will give you reasonably formatted output, like Duration::from_millis(54321) will format as 54.321s, whereas Duration::from_millis(321) will format as 321ms. Not appropriate for every situation, but works pretty well for logging.
this post was submitted on 20 Mar 2026
17 points (100.0% liked)

Rust Programming

9198 readers
55 users here now

founded 7 years ago
MODERATORS