thiserror icon indicating copy to clipboard operation
thiserror copied to clipboard

Support for tracing with `Std::panic::Location` (Feature Request)

Open mhgolkar opened this issue 4 years ago • 3 comments

Hello there

It's sometime useful to simply trace the location of an error's origin, through nested callers and micro managed errors. Compared to already existing Backtrace, it might be more concise, and thanks to std::panic::Location and #[track_caller] being stabilized it wouldn't need nightly.

Thanks for the great crate

mhgolkar avatar Jul 15 '21 11:07 mhgolkar

I also think some kind of backtrace chaining through source errors is really needed for thiserror.

Allen-Webb avatar Oct 06 '21 11:10 Allen-Webb

Anyone know if there are plans to implement this? It looks like it should be pretty easy. A basic implementation looks like this

// New error type encapsulating the original error and location data.
#[derive(Debug, Clone)]
struct LocatedError<E: Error + 'static> {
    inner: E,
    location: &'static Location<'static>,
}

impl<E: Error + 'static> Error for LocatedError<E> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.inner)
    }
}

impl<E: Error + 'static> std::fmt::Display for LocatedError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}, {}", self.inner, self.location)
    }
}

impl From<std::io::Error> for LocatedError<std::io::Error> {
    // The magic happens here
    #[track_caller]
    fn from(err: std::io::Error) -> Self {
        LocatedError {
            inner: err,
            location: std::panic::Location::caller(),
        }
    }
}

To me this feature is basically begging to be included in thiserror.

0xForerunner avatar Feb 11 '23 22:02 0xForerunner