#![cfg_attr(feature = "nightly", feature(try_trait_v2))]
#[cfg(feature = "nightly")]
pub mod nightly;
use std::{
backtrace::{Backtrace, BacktraceStatus},
cell::RefCell,
error::Error,
};
thread_local! {
static BACKTRACE: RefCell<Option<Backtrace>> = const { RefCell::new(None) };
}
fn print_backtrace(backtrace: &Backtrace) {
let backtrace_string = backtrace.to_string();
let mut backtrace_lines = backtrace_string.lines();
backtrace_lines.next();
backtrace_lines.next();
let backtrace_string: String = backtrace_lines.map(|x| x.to_owned() + "\n").collect();
println!("Error Backtrace:\n{}\n", backtrace_string);
}
pub trait ErrorBacktrace {
fn trace(self) -> Self
where
Self: Sized,
{
#[cfg(all(feature = "debug-only", not(debug_assertions)))]
return self;
if !self.is_error() {
return self;
}
let backtrace = Backtrace::capture();
match backtrace.status() {
BacktraceStatus::Unsupported => {
println!("Backtrace is not supported on this platform");
}
BacktraceStatus::Disabled => {
return self;
}
BacktraceStatus::Captured => {}
_ => unreachable!(),
}
BACKTRACE.set(Some(backtrace));
self
}
fn backtrace(self) -> Self
where
Self: Sized,
{
#[cfg(all(feature = "debug-only", not(debug_assertions)))]
return self;
if !self.is_error() {
return self;
}
let backtrace = BACKTRACE.take();
if let Some(backtrace) = backtrace {
print_backtrace(&backtrace);
}
self
}
fn handle_error(self) -> Self
where
Self: Sized,
{
BACKTRACE.take();
self
}
fn is_error(&self) -> bool;
}
impl<T, E> ErrorBacktrace for core::result::Result<T, E> {
fn is_error(&self) -> bool {
self.is_err()
}
}
impl<T1> ErrorBacktrace for core::option::Option<T1> {
fn is_error(&self) -> bool {
self.is_none()
}
}
impl ErrorBacktrace for dyn Error {
fn is_error(&self) -> bool {
true
}
}