error.rs
This file
Path
src/error.rs
606 lines · 17.3 KiB · Rust
Last changed by
Format with rustfmt 2019-09-08David Tolnaybefore adoptiona727067
History of this fileTake it
1use crate::backtrace::Backtrace;2use crate::context::ContextError;3use std::any::TypeId;4use std::error::Error as StdError;5use std::fmt::{self, Debug, Display};6use std::mem::{self, ManuallyDrop};7use std::ops::{Deref, DerefMut};8use std::ptr;910/// The `Error` type, a wrapper around a dynamic error type.11///12/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these13/// differences:14///15/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.16/// - `Error` guarantees that a backtrace is available, even if the underlying17/// error type does not provide one.18/// - `Error` is represented as a narrow pointer — exactly one word in19/// size instead of two.20pub struct Error {21 inner: ManuallyDrop<Box<ErrorImpl<()>>>,22}2324impl Error {25 /// Create a new error object from any error type.26 ///27 /// The error type must be threadsafe and `'static`, so that the `Error`28 /// will be as well.29 ///30 /// If the error type does not provide a backtrace, a backtrace will be31 /// created here to ensure that a backtrace exists.32 pub fn new<E>(error: E) -> Self33 where34 E: StdError + Send + Sync + 'static,35 {36 let backtrace = backtrace_if_absent!(error);37 Error::from_std(error, backtrace)38 }3940 pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self41 where42 E: StdError + Send + Sync + 'static,43 {44 let type_id = TypeId::of::<E>();4546 // Safety: passing typeid of the right type E.47 unsafe { Error::construct(error, type_id, backtrace) }48 }4950 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self51 where52 M: Display + Debug + Send + Sync + 'static,53 {54 let error = MessageError(message);55 let type_id = TypeId::of::<M>();5657 // Safety: MessageError is repr(transparent) so MessageError<M> has the58 // same layout as the typeid specifies.59 unsafe { Error::construct(error, type_id, backtrace) }60 }6162 pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self63 where64 M: Display + Send + Sync + 'static,65 {66 let error = DisplayError(message);67 let type_id = TypeId::of::<M>();6869 // Safety: DisplayError is repr(transparent) so DisplayError<M> has the70 // same layout as the typeid specifies.71 unsafe { Error::construct(error, type_id, backtrace) }72 }7374 // Takes backtrace as argument rather than capturing it here so that the75 // user sees one fewer layer of wrapping noise in the backtrace.76 //77 // Unsafe because the type represented by type_id must have the same layout78 // as E or else we allow invalid downcasts.79 unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> Self80 where81 E: StdError + Send + Sync + 'static,82 {83 let vtable = &ErrorVTable {84 object_drop: object_drop::<E>,85 object_drop_front: object_drop_front::<E>,86 object_ref: object_ref::<E>,87 object_mut: object_mut::<E>,88 object_boxed: object_boxed::<E>,89 };90 let inner = Box::new(ErrorImpl {91 vtable,92 type_id,93 backtrace,94 _error: error,95 });96 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);97 let inner = ManuallyDrop::new(erased);98 Error { inner }99 }100101 /// Wrap the error value with additional context.102 ///103 /// For attaching context to a `Result` as it is propagated, the104 /// [`Context`][crate::Context] extension trait may be more convenient than105 /// this function.106 ///107 /// The primary reason to use `error.context(...)` instead of108 /// `result.context(...)` via the `Context` trait would be if the context109 /// needs to depend on some data held by the underlying error:110 ///111 /// ```112 /// # use std::fmt::{self, Debug, Display};113 /// #114 /// # type T = ();115 /// #116 /// # impl std::error::Error for ParseError {}117 /// # impl Debug for ParseError {118 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {119 /// # unimplemented!()120 /// # }121 /// # }122 /// # impl Display for ParseError {123 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {124 /// # unimplemented!()125 /// # }126 /// # }127 /// #128 /// use anyhow::Result;129 /// use std::fs::File;130 /// use std::path::Path;131 ///132 /// struct ParseError {133 /// line: usize,134 /// column: usize,135 /// }136 ///137 /// fn parse_impl(file: File) -> Result<T, ParseError> {138 /// # const IGNORE: &str = stringify! {139 /// ...140 /// # };141 /// # unimplemented!()142 /// }143 ///144 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {145 /// let file = File::open(&path)?;146 /// parse_impl(file).map_err(|error| {147 /// let context = format!(148 /// "only the first {} lines of {} are valid",149 /// error.line, path.as_ref().display(),150 /// );151 /// anyhow::Error::new(error).context(context)152 /// })153 /// }154 /// ```155 pub fn context<C>(self, context: C) -> Self156 where157 C: Display + Send + Sync + 'static,158 {159 Error::new(ContextError {160 error: self,161 context,162 })163 }164165 /// Get the backtrace for this Error.166 ///167 /// Backtraces are only available on the nightly channel. Tracking issue:168 /// [rust-lang/rust#53487][tracking].169 ///170 /// In order for the backtrace to be meaningful, the environment variable171 /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat172 /// expensive to capture in Rust, so we don't necessarily want to be173 /// capturing them all over the place all the time.174 ///175 /// [tracking]: https://github.com/rust-lang/rust/issues/53487176 #[cfg(backtrace)]177 pub fn backtrace(&self) -> &Backtrace {178 self.inner.backtrace()179 }180181 /// An iterator of the chain of source errors contained by this Error.182 ///183 /// This iterator will visit every error in the cause chain of this error184 /// object, beginning with the error that this error object was created185 /// from.186 ///187 /// # Example188 ///189 /// ```190 /// use anyhow::Error;191 /// use std::io;192 ///193 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {194 /// for cause in error.chain() {195 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {196 /// return Some(io_error.kind());197 /// }198 /// }199 /// None200 /// }201 /// ```202 pub fn chain(&self) -> Chain {203 self.inner.chain()204 }205206 /// The lowest level cause of this error — this error's cause's207 /// cause's cause etc.208 ///209 /// The root cause is the last error in the iterator produced by210 /// [`chain()`][Error::chain].211 pub fn root_cause(&self) -> &(dyn StdError + 'static) {212 let mut chain = self.chain();213 let mut root_cause = chain.next().unwrap();214 for cause in chain {215 root_cause = cause;216 }217 root_cause218 }219220 /// Returns `true` if `E` is the type wrapped by this error object.221 pub fn is<E>(&self) -> bool222 where223 E: Display + Debug + Send + Sync + 'static,224 {225 TypeId::of::<E>() == self.inner.type_id226 }227228 /// Attempt to downcast the error object to a concrete type.229 pub fn downcast<E>(self) -> Result<E, Self>230 where231 E: Display + Debug + Send + Sync + 'static,232 {233 if self.is::<E>() {234 let outer = ManuallyDrop::new(self);235 unsafe {236 let error = ptr::read(237 outer.inner.error() as *const (dyn StdError + Send + Sync) as *const E238 );239 let inner = ptr::read(&outer.inner);240 let erased = ManuallyDrop::into_inner(inner);241 (erased.vtable.object_drop_front)(erased);242 Ok(error)243 }244 } else {245 Err(self)246 }247 }248249 /// Downcast this error object by reference.250 ///251 /// # Example252 ///253 /// ```254 /// # use anyhow::anyhow;255 /// # use std::fmt::{self, Display};256 /// # use std::task::Poll;257 /// #258 /// # #[derive(Debug)]259 /// # enum DataStoreError {260 /// # Censored(()),261 /// # }262 /// #263 /// # impl Display for DataStoreError {264 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {265 /// # unimplemented!()266 /// # }267 /// # }268 /// #269 /// # impl std::error::Error for DataStoreError {}270 /// #271 /// # const REDACTED_CONTENT: () = ();272 /// #273 /// # let error = anyhow!("...");274 /// # let root_cause = &error;275 /// #276 /// # let ret =277 /// // If the error was caused by redaction, then return a tombstone instead278 /// // of the content.279 /// match root_cause.downcast_ref::<DataStoreError>() {280 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),281 /// None => Err(error),282 /// }283 /// # ;284 /// ```285 pub fn downcast_ref<E>(&self) -> Option<&E>286 where287 E: Display + Debug + Send + Sync + 'static,288 {289 if self.is::<E>() {290 Some(unsafe {291 &*(self.inner.error() as *const (dyn StdError + Send + Sync) as *const E)292 })293 } else {294 None295 }296 }297298 /// Downcast this error object by mutable reference.299 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>300 where301 E: Display + Debug + Send + Sync + 'static,302 {303 if self.is::<E>() {304 Some(unsafe {305 &mut *(self.inner.error_mut() as *mut (dyn StdError + Send + Sync) as *mut E)306 })307 } else {308 None309 }310 }311}312313impl<E> From<E> for Error314where315 E: StdError + Send + Sync + 'static,316{317 fn from(error: E) -> Self {318 let backtrace = backtrace_if_absent!(error);319 Error::from_std(error, backtrace)320 }321}322323impl Deref for Error {324 type Target = dyn StdError + Send + Sync + 'static;325326 fn deref(&self) -> &Self::Target {327 self.inner.error()328 }329}330331impl DerefMut for Error {332 fn deref_mut(&mut self) -> &mut Self::Target {333 self.inner.error_mut()334 }335}336337impl Debug for Error {338 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {339 self.inner.debug(formatter)340 }341}342343impl Display for Error {344 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {345 write!(f, "{}", self.inner.error())346 }347}348349unsafe impl Send for Error {}350unsafe impl Sync for Error {}351352impl Drop for Error {353 fn drop(&mut self) {354 unsafe {355 let inner = ptr::read(&self.inner);356 let erased = ManuallyDrop::into_inner(inner);357 (erased.vtable.object_drop)(erased);358 }359 }360}361362struct ErrorVTable {363 object_drop: unsafe fn(Box<ErrorImpl<()>>),364 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),365 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),366 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),367 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,368}369370unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {371 // Cast back to ErrorImpl<E> so that the allocator receives the correct372 // Layout to deallocate the Box's memory.373 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);374 drop(unerased);375}376377unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {378 // Drop the fields of ErrorImpl other than E as well as the Box allocation,379 // without dropping E itself. This is used by downcast after doing a380 // ptr::read to take ownership of the E.381 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);382 drop(unerased);383}384385unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)386where387 E: StdError + Send + Sync + 'static,388{389 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._error390}391392unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)393where394 E: StdError + Send + Sync + 'static,395{396 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._error397}398399unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>400where401 E: StdError + Send + Sync + 'static,402{403 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)404}405406// repr C to ensure that `E` remains in the final position407#[repr(C)]408struct ErrorImpl<E> {409 vtable: &'static ErrorVTable,410 type_id: TypeId,411 backtrace: Option<Backtrace>,412 // NOTE: Don't use directly. Use only through vtable. Erased type may have different alignment.413 _error: E,414}415416#[repr(transparent)]417struct MessageError<M>(M);418419impl<M> Debug for MessageError<M>420where421 M: Display + Debug,422{423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {424 Debug::fmt(&self.0, f)425 }426}427428impl<M> Display for MessageError<M>429where430 M: Display + Debug,431{432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {433 Display::fmt(&self.0, f)434 }435}436437impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}438439#[repr(transparent)]440struct DisplayError<M>(M);441442impl<M> Debug for DisplayError<M>443where444 M: Display,445{446 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {447 Display::fmt(&self.0, f)448 }449}450451impl<M> Display for DisplayError<M>452where453 M: Display,454{455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {456 Display::fmt(&self.0, f)457 }458}459460impl<M> StdError for DisplayError<M> where M: Display + 'static {}461462impl<E> ErrorImpl<E> {463 fn erase(&self) -> &ErrorImpl<()> {464 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }465 }466}467468impl ErrorImpl<()> {469 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {470 unsafe { &*(self.vtable.object_ref)(self) }471 }472473 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {474 unsafe { &mut *(self.vtable.object_mut)(self) }475 }476477 #[cfg(backtrace)]478 fn backtrace(&self) -> &Backtrace {479 // This unwrap can only panic if the underlying error's backtrace method480 // is nondeterministic, which would only happen in maliciously481 // constructed code.482 self.backtrace483 .as_ref()484 .or_else(|| self.error().backtrace())485 .expect("backtrace capture failed")486 }487488 fn chain(&self) -> Chain {489 Chain {490 next: Some(self.error()),491 }492 }493494 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {495 writeln!(f, "{}", self.error())?;496497 let mut chain = self.chain().skip(1).enumerate().peekable();498 if let Some((n, error)) = chain.next() {499 write!(f, "\nCaused by:\n ")?;500 if chain.peek().is_some() {501 write!(f, "{}: ", n)?;502 }503 writeln!(f, "{}", error)?;504 for (n, error) in chain {505 writeln!(f, " {}: {}", n, error)?;506 }507 }508509 #[cfg(backtrace)]510 {511 use std::backtrace::BacktraceStatus;512513 let backtrace = self.backtrace();514 match backtrace.status() {515 BacktraceStatus::Captured => {516 writeln!(f, "\n{}", backtrace)?;517 }518 BacktraceStatus::Disabled => {519 writeln!(520 f,521 "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"522 )?;523 }524 _ => {}525 }526 }527528 Ok(())529 }530}531532impl<E> StdError for ErrorImpl<E>533where534 E: StdError,535{536 #[cfg(backtrace)]537 fn backtrace(&self) -> Option<&Backtrace> {538 Some(self.erase().backtrace())539 }540541 fn source(&self) -> Option<&(dyn StdError + 'static)> {542 self.erase().error().source()543 }544}545546impl<E> Debug for ErrorImpl<E>547where548 E: Debug,549{550 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {551 self.erase().debug(formatter)552 }553}554555impl<E> Display for ErrorImpl<E>556where557 E: Display,558{559 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {560 Display::fmt(&self.erase().error(), formatter)561 }562}563564impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {565 fn from(error: Error) -> Self {566 let outer = ManuallyDrop::new(error);567 unsafe {568 let inner = ptr::read(&outer.inner);569 let erased = ManuallyDrop::into_inner(inner);570 (erased.vtable.object_boxed)(erased)571 }572 }573}574575/// Iterator of a chain of source errors.576///577/// This type is the iterator returned by [`Error::chain`].578///579/// # Example580///581/// ```582/// use anyhow::Error;583/// use std::io;584///585/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {586/// for cause in error.chain() {587/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {588/// return Some(io_error.kind());589/// }590/// }591/// None592/// }593/// ```594pub struct Chain<'a> {595 next: Option<&'a (dyn StdError + 'static)>,596}597598impl<'a> Iterator for Chain<'a> {599 type Item = &'a (dyn StdError + 'static);600601 fn next(&mut self) -> Option<Self::Item> {602 let next = self.next.take()?;603 self.next = next.source();604 Some(next)605 }606}