error.rs
This file
Path
src/error.rs
599 lines · 16.9 KiB · Rust
Last changed by
Fill in StdError methods for ErrorImplDavid Tolnaybefore adoptionabd2452
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_raw: object_raw::<E>,87 object_mut_raw: object_mut_raw::<E>,88 object_boxed: object_boxed::<E>,89 };90 let inner = Box::new(ErrorImpl {91 vtable,92 type_id,93 backtrace,94 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(&outer.inner.error as *const () as *const E);237 let inner = ptr::read(&outer.inner);238 let erased = ManuallyDrop::into_inner(inner);239 (erased.vtable.object_drop_front)(erased);240 Ok(error)241 }242 } else {243 Err(self)244 }245 }246247 /// Downcast this error object by reference.248 ///249 /// # Example250 ///251 /// ```252 /// # use anyhow::anyhow;253 /// # use std::fmt::{self, Display};254 /// # use std::task::Poll;255 /// #256 /// # #[derive(Debug)]257 /// # enum DataStoreError {258 /// # Censored(()),259 /// # }260 /// #261 /// # impl Display for DataStoreError {262 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {263 /// # unimplemented!()264 /// # }265 /// # }266 /// #267 /// # impl std::error::Error for DataStoreError {}268 /// #269 /// # const REDACTED_CONTENT: () = ();270 /// #271 /// # let error = anyhow!("...");272 /// # let root_cause = &error;273 /// #274 /// # let ret =275 /// // If the error was caused by redaction, then return a tombstone instead276 /// // of the content.277 /// match root_cause.downcast_ref::<DataStoreError>() {278 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),279 /// None => Err(error),280 /// }281 /// # ;282 /// ```283 pub fn downcast_ref<E>(&self) -> Option<&E>284 where285 E: Display + Debug + Send + Sync + 'static,286 {287 if self.is::<E>() {288 Some(unsafe { &*(&self.inner.error as *const () as *const E) })289 } else {290 None291 }292 }293294 /// Downcast this error object by mutable reference.295 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>296 where297 E: Display + Debug + Send + Sync + 'static,298 {299 if self.is::<E>() {300 Some(unsafe { &mut *(&mut self.inner.error as *mut () as *mut E) })301 } else {302 None303 }304 }305}306307impl<E> From<E> for Error308where309 E: StdError + Send + Sync + 'static,310{311 fn from(error: E) -> Self {312 let backtrace = backtrace_if_absent!(error);313 Error::from_std(error, backtrace)314 }315}316317impl Deref for Error {318 type Target = dyn StdError + Send + Sync + 'static;319320 fn deref(&self) -> &Self::Target {321 self.inner.error()322 }323}324325impl DerefMut for Error {326 fn deref_mut(&mut self) -> &mut Self::Target {327 self.inner.error_mut()328 }329}330331impl Debug for Error {332 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {333 self.inner.debug(formatter)334 }335}336337impl Display for Error {338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {339 write!(f, "{}", self.inner.error())340 }341}342343unsafe impl Send for Error {}344unsafe impl Sync for Error {}345346impl Drop for Error {347 fn drop(&mut self) {348 unsafe {349 let inner = ptr::read(&self.inner);350 let erased = ManuallyDrop::into_inner(inner);351 (erased.vtable.object_drop)(erased);352 }353 }354}355356struct ErrorVTable {357 object_drop: unsafe fn(Box<ErrorImpl<()>>),358 object_drop_front: unsafe fn(Box<ErrorImpl<()>>),359 object_raw: fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),360 object_mut_raw: fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),361 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,362}363364unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {365 // Cast back to ErrorImpl<E> so that the allocator receives the correct366 // Layout to deallocate the Box's memory.367 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);368 drop(unerased);369}370371unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {372 // Drop the fields of ErrorImpl other than E as well as the Box allocation,373 // without dropping E itself. This is used by downcast after doing a374 // ptr::read to take ownership of the E.375 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);376 drop(unerased);377}378379fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)380where381 E: StdError + Send + Sync + 'static,382{383 e as *const E384}385386fn object_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)387where388 E: StdError + Send + Sync + 'static,389{390 e as *mut E391}392393unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>394where395 E: StdError + Send + Sync + 'static,396{397 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)398}399400// repr C to ensure that `E` remains in the final position401#[repr(C)]402struct ErrorImpl<E> {403 vtable: &'static ErrorVTable,404 type_id: TypeId,405 backtrace: Option<Backtrace>,406 error: E,407}408409#[repr(transparent)]410struct MessageError<M>(M);411412impl<M> Debug for MessageError<M>413where414 M: Display + Debug,415{416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {417 Debug::fmt(&self.0, f)418 }419}420421impl<M> Display for MessageError<M>422where423 M: Display + Debug,424{425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {426 Display::fmt(&self.0, f)427 }428}429430impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}431432#[repr(transparent)]433struct DisplayError<M>(M);434435impl<M> Debug for DisplayError<M>436where437 M: Display,438{439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {440 Display::fmt(&self.0, f)441 }442}443444impl<M> Display for DisplayError<M>445where446 M: Display,447{448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {449 Display::fmt(&self.0, f)450 }451}452453impl<M> StdError for DisplayError<M> where M: Display + 'static {}454455impl<E> ErrorImpl<E> {456 fn erase(&self) -> &ErrorImpl<()> {457 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }458 }459}460461impl ErrorImpl<()> {462 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {463 unsafe { &*(self.vtable.object_raw)(&self.error) }464 }465466 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {467 unsafe { &mut *(self.vtable.object_mut_raw)(&mut self.error) }468 }469470 #[cfg(backtrace)]471 fn backtrace(&self) -> &Backtrace {472 // This unwrap can only panic if the underlying error's backtrace method473 // is nondeterministic, which would only happen in maliciously474 // constructed code.475 self.backtrace476 .as_ref()477 .or_else(|| self.error().backtrace())478 .expect("backtrace capture failed")479 }480481 fn chain(&self) -> Chain {482 Chain {483 next: Some(self.error()),484 }485 }486487 fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {488 writeln!(f, "{}", self.error())?;489490 let mut chain = self.chain().skip(1).enumerate().peekable();491 if let Some((n, error)) = chain.next() {492 write!(f, "\nCaused by:\n ")?;493 if chain.peek().is_some() {494 write!(f, "{}: ", n)?;495 }496 writeln!(f, "{}", error)?;497 for (n, error) in chain {498 writeln!(f, " {}: {}", n, error)?;499 }500 }501502 #[cfg(backtrace)]503 {504 use std::backtrace::BacktraceStatus;505506 let backtrace = self.backtrace();507 match backtrace.status() {508 BacktraceStatus::Captured => {509 writeln!(f, "\n{}", backtrace)?;510 }511 BacktraceStatus::Disabled => {512 writeln!(513 f,514 "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"515 )?;516 }517 _ => {}518 }519 }520521 Ok(())522 }523}524525impl<E> StdError for ErrorImpl<E>526where527 E: StdError,528{529 #[cfg(backtrace)]530 fn backtrace(&self) -> Option<&Backtrace> {531 Some(self.erase().backtrace())532 }533534 fn source(&self) -> Option<&(dyn StdError + 'static)> {535 self.error.source()536 }537}538539impl<E> Debug for ErrorImpl<E>540where541 E: Debug,542{543 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {544 self.erase().debug(formatter)545 }546}547548impl<E> Display for ErrorImpl<E>549where550 E: Display,551{552 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {553 Display::fmt(&self.error, formatter)554 }555}556557impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {558 fn from(error: Error) -> Self {559 let outer = ManuallyDrop::new(error);560 unsafe {561 let inner = ptr::read(&outer.inner);562 let erased = ManuallyDrop::into_inner(inner);563 (erased.vtable.object_boxed)(erased)564 }565 }566}567568/// Iterator of a chain of source errors.569///570/// This type is the iterator returned by [`Error::chain`].571///572/// # Example573///574/// ```575/// use anyhow::Error;576/// use std::io;577///578/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {579/// for cause in error.chain() {580/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {581/// return Some(io_error.kind());582/// }583/// }584/// None585/// }586/// ```587pub struct Chain<'a> {588 next: Option<&'a (dyn StdError + 'static)>,589}590591impl<'a> Iterator for Chain<'a> {592 type Item = &'a (dyn StdError + 'static);593594 fn next(&mut self) -> Option<Self::Item> {595 let next = self.next.take()?;596 self.next = next.source();597 Some(next)598 }599}