Skip to content
Myr

error.rs

This file

Path

src/error.rs

508 lines · 13.8 KiB · Rust

Last changed by

Capitalize lines of Debug representationDavid Tolnaybefore adoptiona97f8dc

History of this file

Take it

1use crate::context::ContextError;2use std::any::TypeId;3use std::error::Error as StdError;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89#[cfg(backtrace)]10use std::backtrace::{Backtrace, BacktraceStatus};1112/// The `Error` type, a wrapper around a dynamic error type.13///14/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these15/// differences:16///17/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.18/// - `Error` guarantees that a backtrace is available, even if the underlying19///   error type does not provide one.20/// - `Error` is represented as a narrow pointer &mdash; exactly one word in21///   size instead of two.22pub struct Error {23    inner: Box<ErrorImpl<()>>,24}2526impl Error {27    /// Create a new error object from any error type.28    ///29    /// The error type must be threadsafe and `'static`, so that the `Error`30    /// will be as well.31    ///32    /// If the error type does not provide a backtrace, a backtrace will be33    /// created here to ensure that a backtrace exists.34    pub fn new<E>(error: E) -> Self35    where36        E: StdError + Send + Sync + 'static,37    {38        // Captured here instead of in Error::construct to have one fewer layer39        // of wrapping visible in the backtrace.40        #[cfg(backtrace)]41        let backtrace = match error.backtrace() {42            Some(_) => None,43            None => Some(Backtrace::capture()),44        };4546        #[cfg(not(backtrace))]47        let backtrace = None;4849        Error::construct(error, TypeId::of::<E>(), backtrace)50    }5152    pub(crate) fn new_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self53    where54        M: Display + Debug + Send + Sync + 'static,55    {56        Error::construct(MessageError(message), TypeId::of::<M>(), backtrace)57    }5859    fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self60    where61        E: StdError + Send + Sync + 'static,62    {63        unsafe {64            let obj = mem::transmute::<&dyn StdError, TraitObject>(&error);65            let inner = Box::new(ErrorImpl {66                vtable: obj.vtable,67                type_id,68                backtrace,69                error,70            });71            Error {72                inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),73            }74        }75    }7677    /// Wrap the error value with additional context.78    ///79    /// For attaching context to a `Result` as it is propagated, the80    /// [`Context`][crate::Context] extension trait may be more convenient than81    /// this function.82    ///83    /// The primary reason to use `error.context(...)` instead of84    /// `result.context(...)` via the `Context` trait would be if the context85    /// needs to depend on some data held by the underlying error:86    ///87    /// ```88    /// # use std::fmt::{self, Debug, Display};89    /// #90    /// # type T = ();91    /// #92    /// # impl std::error::Error for ParseError {}93    /// # impl Debug for ParseError {94    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {95    /// #         unimplemented!()96    /// #     }97    /// # }98    /// # impl Display for ParseError {99    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {100    /// #         unimplemented!()101    /// #     }102    /// # }103    /// #104    /// use std::fs::File;105    /// use std::path::Path;106    ///107    /// struct ParseError {108    ///     line: usize,109    ///     column: usize,110    /// }111    ///112    /// fn parse_impl(file: File) -> Result<T, ParseError> {113    ///     # const IGNORE: &str = stringify! {114    ///     ...115    ///     # };116    ///     # unimplemented!()117    /// }118    ///119    /// pub fn parse(path: impl AsRef<Path>) -> anyhow::Result<T> {120    ///     let file = File::open(&path)?;121    ///     parse_impl(file).map_err(|error| {122    ///         let context = format!(123    ///             "only the first {} lines of {} are valid",124    ///             error.line, path.as_ref().display(),125    ///         );126    ///         anyhow::Error::new(error).context(context)127    ///     })128    /// }129    /// ```130    pub fn context<C>(self, context: C) -> Self131    where132        C: Display + Send + Sync + 'static,133    {134        Error::from(ContextError {135            error: self,136            context,137        })138    }139140    /// Get the backtrace for this Error.141    ///142    /// Backtraces are only available on the nightly channel. Tracking issue:143    /// [rust-lang/rust#53487][tracking].144    ///145    /// In order for the backtrace to be meaningful, the environment variable146    /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat147    /// expensive to capture in Rust, so we don't necessarily want to be148    /// capturing them all over the place all the time.149    ///150    /// [tracking]: https://github.com/rust-lang/rust/issues/53487151    #[cfg(backtrace)]152    pub fn backtrace(&self) -> &Backtrace {153        // NB: this unwrap can only fail if the underlying error's backtrace154        // method is nondeterministic, which would only happen in maliciously155        // constructed code156        self.inner157            .backtrace158            .as_ref()159            .or_else(|| self.inner.error().backtrace())160            .expect("backtrace capture failed")161    }162163    /// An iterator of the chain of source errors contained by this Error.164    ///165    /// This iterator will visit every error in the cause chain of this error166    /// object, beginning with the error that this error object was created167    /// from.168    ///169    /// # Example170    ///171    /// ```172    /// use anyhow::Error;173    /// use std::io;174    ///175    /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {176    ///     for cause in error.chain() {177    ///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {178    ///             return Some(io_error.kind());179    ///         }180    ///     }181    ///     None182    /// }183    /// ```184    pub fn chain(&self) -> Chain {185        Chain {186            next: Some(self.inner.error()),187        }188    }189190    /// The lowest level cause of this error &mdash; this error's cause's191    /// cause's cause etc.192    ///193    /// The root cause is the last error in the iterator produced by194    /// [`chain()`][Error::chain].195    pub fn root_cause(&self) -> &(dyn StdError + 'static) {196        let mut chain = self.chain();197        let mut root_cause = chain.next().unwrap();198        for cause in chain {199            root_cause = cause;200        }201        root_cause202    }203204    /// Returns `true` if `E` is the type wrapped by this error object.205    pub fn is<E>(&self) -> bool206    where207        E: Display + Debug + Send + Sync + 'static,208    {209        TypeId::of::<E>() == self.inner.type_id210    }211212    /// Attempt to downcast the error object to a concrete type.213    pub fn downcast<E>(self) -> Result<E, Self>214    where215        E: Display + Debug + Send + Sync + 'static,216    {217        if let Some(error) = self.downcast_ref::<E>() {218            unsafe {219                let error = ptr::read(error);220                drop(ptr::read(&self.inner));221                mem::forget(self);222                Ok(error)223            }224        } else {225            Err(self)226        }227    }228229    /// Downcast this error object by reference.230    ///231    /// # Example232    ///233    /// ```234    /// # use anyhow::anyhow;235    /// # use std::fmt::{self, Display};236    /// # use std::task::Poll;237    /// #238    /// # #[derive(Debug)]239    /// # enum DataStoreError {240    /// #     Censored(()),241    /// # }242    /// #243    /// # impl Display for DataStoreError {244    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {245    /// #         unimplemented!()246    /// #     }247    /// # }248    /// #249    /// # impl std::error::Error for DataStoreError {}250    /// #251    /// # const REDACTED_CONTENT: () = ();252    /// #253    /// # let error = anyhow!("...");254    /// # let root_cause = &error;255    /// #256    /// # let ret =257    /// // If the error was caused by redaction, then return a tombstone instead258    /// // of the content.259    /// match root_cause.downcast_ref::<DataStoreError>() {260    ///     Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),261    ///     None => Err(error),262    /// }263    /// # ;264    /// ```265    pub fn downcast_ref<E>(&self) -> Option<&E>266    where267        E: Display + Debug + Send + Sync + 'static,268    {269        if self.is::<E>() {270            unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }271        } else {272            None273        }274    }275276    /// Downcast this error object by mutable reference.277    pub fn downcast_mut<E>(&mut self) -> Option<&mut E>278    where279        E: Display + Debug + Send + Sync + 'static,280    {281        if self.is::<E>() {282            unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }283        } else {284            None285        }286    }287}288289#[cfg(not(backtrace))]290pub(crate) enum Backtrace {}291292impl<E> From<E> for Error293where294    E: StdError + Send + Sync + 'static,295{296    fn from(error: E) -> Self {297        Error::new(error)298    }299}300301impl Deref for Error {302    type Target = dyn StdError + Send + Sync + 'static;303304    fn deref(&self) -> &Self::Target {305        self.inner.error()306    }307}308309impl DerefMut for Error {310    fn deref_mut(&mut self) -> &mut Self::Target {311        self.inner.error_mut()312    }313}314315impl Debug for Error {316    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {317        writeln!(f, "{}", self.inner.error())?;318319        let mut chain = self.chain().skip(1).enumerate();320        if let Some((n, error)) = chain.next() {321            writeln!(f, "\nCaused by:")?;322            writeln!(f, "\t{}: {}", n, error)?;323            for (n, error) in chain {324                writeln!(f, "\t{}: {}", n, error)?;325            }326        }327328        #[cfg(backtrace)]329        {330            let backtrace = self.backtrace();331            match backtrace.status() {332                BacktraceStatus::Captured => {333                    writeln!(f, "\n{}", backtrace)?;334                }335                BacktraceStatus::Disabled => {336                    writeln!(337                        f,338                        "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"339                    )?;340                }341                _ => {}342            }343        }344345        Ok(())346    }347}348349impl Display for Error {350    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {351        write!(f, "{}", self.inner.error())352    }353}354355unsafe impl Send for Error {}356unsafe impl Sync for Error {}357358impl Drop for Error {359    fn drop(&mut self) {360        unsafe { ptr::drop_in_place(self.inner.error_mut()) }361    }362}363364// repr C to ensure that `E` remains in the final position365#[repr(C)]366struct ErrorImpl<E> {367    vtable: *const (),368    type_id: TypeId,369    backtrace: Option<Backtrace>,370    error: E,371}372373// repr C to ensure that transmuting from trait objects is safe374#[repr(C)]375struct TraitObject {376    data: *const (),377    vtable: *const (),378}379380#[repr(transparent)]381struct MessageError<M>(M);382383impl<M> Debug for MessageError<M>384where385    M: Display + Debug,386{387    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {388        Debug::fmt(&self.0, f)389    }390}391392impl<M> Display for MessageError<M>393where394    M: Display + Debug,395{396    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {397        Display::fmt(&self.0, f)398    }399}400401impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}402403impl ErrorImpl<()> {404    fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {405        let object = TraitObject {406            data: &self.error,407            vtable: self.vtable,408        };409410        unsafe { mem::transmute::<TraitObject, &(dyn StdError + Send + Sync + 'static)>(object) }411    }412413    fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {414        let object = TraitObject {415            data: &mut self.error,416            vtable: self.vtable,417        };418419        unsafe {420            mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)421        }422    }423}424425/// Iterator of a chain of source errors.426///427/// This type is the iterator returned by [`Error::chain`].428///429/// # Example430///431/// ```432/// use anyhow::Error;433/// use std::io;434///435/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {436///     for cause in error.chain() {437///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {438///             return Some(io_error.kind());439///         }440///     }441///     None442/// }443/// ```444pub struct Chain<'a> {445    next: Option<&'a (dyn StdError + 'static)>,446}447448impl<'a> Iterator for Chain<'a> {449    type Item = &'a (dyn StdError + 'static);450451    fn next(&mut self) -> Option<Self::Item> {452        let next = self.next.take()?;453        self.next = next.source();454        Some(next)455    }456}457458#[cfg(test)]459mod repr_correctness {460    use super::*;461    use std::marker::Unpin;462    use std::mem;463    use std::sync::atomic::AtomicBool;464    use std::sync::atomic::Ordering::SeqCst;465    use std::sync::Arc;466467    #[test]468    fn size_of_error() {469        assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());470    }471472    #[test]473    fn error_autotraits() {474        fn assert<E: Unpin + Send + Sync + 'static>() {}475        assert::<Error>();476    }477478    #[test]479    fn drop_works() {480        #[derive(Debug)]481        struct DetectDrop {482            has_dropped: Arc<AtomicBool>,483        }484485        impl StdError for DetectDrop {}486487        impl Display for DetectDrop {488            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {489                write!(f, "does something")490            }491        }492493        impl Drop for DetectDrop {494            fn drop(&mut self) {495                let already_dropped = self.has_dropped.swap(true, SeqCst);496                assert!(!already_dropped);497            }498        }499500        let has_dropped = Arc::new(AtomicBool::new(false));501502        drop(Error::from(DetectDrop {503            has_dropped: has_dropped.clone(),504        }));505506        assert!(has_dropped.load(SeqCst));507    }508}