Skip to content
Myr

error.rs

This file

Path

src/error.rs

511 lines · 13.9 KiB · Rust

Last changed by

Omit '0:' if only one causeDavid Tolnaybefore adoptionb0c8c75

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().peekable();320        if let Some((n, error)) = chain.next() {321            write!(f, "\nCaused by:\n    ")?;322            if chain.peek().is_some() {323                write!(f, "{}: ", n)?;324            }325            writeln!(f, "{}", error)?;326            for (n, error) in chain {327                writeln!(f, "    {}: {}", n, error)?;328            }329        }330331        #[cfg(backtrace)]332        {333            let backtrace = self.backtrace();334            match backtrace.status() {335                BacktraceStatus::Captured => {336                    writeln!(f, "\n{}", backtrace)?;337                }338                BacktraceStatus::Disabled => {339                    writeln!(340                        f,341                        "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"342                    )?;343                }344                _ => {}345            }346        }347348        Ok(())349    }350}351352impl Display for Error {353    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {354        write!(f, "{}", self.inner.error())355    }356}357358unsafe impl Send for Error {}359unsafe impl Sync for Error {}360361impl Drop for Error {362    fn drop(&mut self) {363        unsafe { ptr::drop_in_place(self.inner.error_mut()) }364    }365}366367// repr C to ensure that `E` remains in the final position368#[repr(C)]369struct ErrorImpl<E> {370    vtable: *const (),371    type_id: TypeId,372    backtrace: Option<Backtrace>,373    error: E,374}375376// repr C to ensure that transmuting from trait objects is safe377#[repr(C)]378struct TraitObject {379    data: *const (),380    vtable: *const (),381}382383#[repr(transparent)]384struct MessageError<M>(M);385386impl<M> Debug for MessageError<M>387where388    M: Display + Debug,389{390    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {391        Debug::fmt(&self.0, f)392    }393}394395impl<M> Display for MessageError<M>396where397    M: Display + Debug,398{399    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {400        Display::fmt(&self.0, f)401    }402}403404impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}405406impl ErrorImpl<()> {407    fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {408        let object = TraitObject {409            data: &self.error,410            vtable: self.vtable,411        };412413        unsafe { mem::transmute::<TraitObject, &(dyn StdError + Send + Sync + 'static)>(object) }414    }415416    fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {417        let object = TraitObject {418            data: &mut self.error,419            vtable: self.vtable,420        };421422        unsafe {423            mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)424        }425    }426}427428/// Iterator of a chain of source errors.429///430/// This type is the iterator returned by [`Error::chain`].431///432/// # Example433///434/// ```435/// use anyhow::Error;436/// use std::io;437///438/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {439///     for cause in error.chain() {440///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {441///             return Some(io_error.kind());442///         }443///     }444///     None445/// }446/// ```447pub struct Chain<'a> {448    next: Option<&'a (dyn StdError + 'static)>,449}450451impl<'a> Iterator for Chain<'a> {452    type Item = &'a (dyn StdError + 'static);453454    fn next(&mut self) -> Option<Self::Item> {455        let next = self.next.take()?;456        self.next = next.source();457        Some(next)458    }459}460461#[cfg(test)]462mod repr_correctness {463    use super::*;464    use std::marker::Unpin;465    use std::mem;466    use std::sync::atomic::AtomicBool;467    use std::sync::atomic::Ordering::SeqCst;468    use std::sync::Arc;469470    #[test]471    fn size_of_error() {472        assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());473    }474475    #[test]476    fn error_autotraits() {477        fn assert<E: Unpin + Send + Sync + 'static>() {}478        assert::<Error>();479    }480481    #[test]482    fn drop_works() {483        #[derive(Debug)]484        struct DetectDrop {485            has_dropped: Arc<AtomicBool>,486        }487488        impl StdError for DetectDrop {}489490        impl Display for DetectDrop {491            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {492                write!(f, "does something")493            }494        }495496        impl Drop for DetectDrop {497            fn drop(&mut self) {498                let already_dropped = self.has_dropped.swap(true, SeqCst);499                assert!(!already_dropped);500            }501        }502503        let has_dropped = Arc::new(AtomicBool::new(false));504505        drop(Error::from(DetectDrop {506            has_dropped: has_dropped.clone(),507        }));508509        assert!(has_dropped.load(SeqCst));510    }511}