This repository has been archived on 2026-03-27. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
tracing/examples/examples/custom-error.rs
Hayden Stainsby bdbaf80073
examples: add note to examples that they are for tracing 0.2.0 (#3099)
It is not uncommon that users who are new to tracing look at the
examples in the `master` branch of the repository and find that they
don't compile. This is because they are examples which compile with the
code from the master branch, which is for the as yet unreleased tracing
0.2.0 ecosystem.

Users should instead go to the `v0.1.x` branch to find examples
compatible with the crates published on crates.io.

This change adds a doc-comment to the beginning of every example file
informing the user of this fact and suggesting that they check out the
`v0.1.x` branch instead.
2024-10-09 15:31:11 -04:00

65 lines
2 KiB
Rust

//! NOTE: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem. For the
//! release examples, please see the `v0.1.x` branch instead.
//!
//! This example demonstrates using the `tracing-error` crate's `SpanTrace` type
//! to attach a trace context to a custom error type.
#![deny(rust_2018_idioms)]
use std::error::Error;
use std::fmt;
use tracing_error::{ErrorSubscriber, SpanTrace};
use tracing_subscriber::prelude::*;
#[derive(Debug)]
struct FooError {
message: &'static str,
// This struct captures the current `tracing` span context when it is
// constructed. Later, when we display this error, we will format this
// captured span trace.
context: SpanTrace,
}
impl FooError {
fn new(message: &'static str) -> Self {
Self {
message,
context: SpanTrace::capture(),
}
}
}
impl Error for FooError {}
impl fmt::Display for FooError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.message)?;
write!(f, "\n\nspan backtrace:\n{}", self.context)?;
write!(f, "\n\ndebug span backtrace: {:?}", self.context)?;
write!(f, "\n\nalt debug span backtrace: {:#?}", self.context)?;
Ok(())
}
}
#[tracing::instrument]
fn do_something(foo: &str) -> Result<&'static str, impl Error + Send + Sync + 'static> {
do_another_thing(42, false)
}
#[tracing::instrument]
fn do_another_thing(
answer: usize,
will_succeed: bool,
) -> Result<&'static str, impl Error + Send + Sync + 'static> {
Err(FooError::new("something broke, lol"))
}
#[tracing::instrument]
fn main() {
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::subscriber())
// The `ErrorSubscriber` subscriber layer enables the use of `SpanTrace`.
.with(ErrorSubscriber::default())
.init();
match do_something("hello world") {
Ok(result) => println!("did something successfully: {}", result),
Err(e) => eprintln!("error: {}", e),
};
}