error.rs
This file
Path
src/error.rs
356 lines · 9.2 KiB · Rust
Last changed by
Recommend RUST_LIB_BACKTRACE=1 variableDavid Tolnaybefore adoption71b360e
History of this fileTake it
Add context method to ErrorDavid Tolnaybefore adoption41fde4c
line 1why, one step back1use crate::context::ContextError;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 2–3why, one step back2use std::any::TypeId;3use std::backtrace::{Backtrace, BacktraceStatus};Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 4why, one step back4use std::error::Error as StdError;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 5–9why, one step back5use std::fmt::{self, Debug, Display};6use std::mem;7use std::ops::{Deref, DerefMut};8use std::ptr;9Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 10why, one step back10/// The `Error` type, a wrapper around a dynamic error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 11why, one step back11///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 12–13why, one step back12/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these13/// differences:Rename exception module to errorDavid Tolnaybefore adoption2000930
line 14why, one step back14///Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 15–16why, one step back15/// - `Error` requires that the error is `Send`, `Sync`, and `'static`16/// - `Error` guarantees that a backtrace will exist, even if the error typeRename exception module to errorDavid Tolnaybefore adoption2000930
line 17why, one step back17/// did not provide oneRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 18why, one step back18/// - `Error` is represented as a narrow pointer - exactly one word in size,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 19why, one step back19/// instead of two.Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 20why, one step back20pub struct Error {Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 21why, one step back21 inner: Box<ErrorImpl<()>>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 22–23why, one step back22}23Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 24why, one step back24impl Error {Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 25why, one step back25 /// Create a new error object from any error type.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 26why, one step back26 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 27–28why, one step back27 /// The error type must be threadsafe and `'static`, so that the `Error`28 /// will be as well.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 29why, one step back29 ///Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 30–31why, one step back30 /// If the error type does not provide a backtrace, a backtrace will be31 /// created here to ensure that a backtrace exists.Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 32why, one step back32 pub fn new<E>(error: E) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
line 33why, one step back33 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 34why, one step back34 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 35why, one step back35 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 36why, one step back36 Error::construct(error, TypeId::of::<E>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 37–39why, one step back37 }3839 #[doc(hidden)]Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 40why, one step back40 pub fn new_adhoc<M>(message: M) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
lines 41–43why, one step back41 where42 M: Display + Debug + Send + Sync + 'static,43 {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 44why, one step back44 Error::construct(MessageError(message), TypeId::of::<M>())Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 45–46why, one step back45 }46Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 47why, one step back47 fn construct<E>(error: E, type_id: TypeId) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
line 48why, one step back48 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 49why, one step back49 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 50why, one step back50 {Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a
lines 51–55why, one step back51 let backtrace = match error.backtrace() {52 Some(_) => None,53 None => Some(Backtrace::capture()),54 };55Rename exception module to errorDavid Tolnaybefore adoption2000930
line 56why, one step back56 unsafe {Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
line 57why, one step back57 let obj = mem::transmute::<&dyn StdError, TraitObject>(&error);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 58why, one step back58 let vtable = obj.vtable;Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
line 59why, one step back59 let inner = Box::new(ErrorImpl {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 60–63why, one step back60 vtable,61 type_id,62 backtrace,63 error,Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
line 64why, one step back64 });Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 65why, one step back65 Error {Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
line 66why, one step back66 inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 67–68why, one step back67 }68 }Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 69–79why, one step back69 }7071 /// Wrap the error value with additional context.72 pub fn context<C>(self, context: C) -> Self73 where74 C: Display + Send + Sync + 'static,75 {76 Error::from(ContextError {77 error: self,78 context,79 })Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 80–81why, one step back80 }81Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 82why, one step back82 /// View this error object as the underlying error.Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383
line 83why, one step back83 pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 84–86why, one step back84 &**self85 }86Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 87why, one step back87 /// View this error object as the underlying error, mutably.Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383
line 88why, one step back88 pub fn as_dyn_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 89–91why, one step back89 &mut **self90 }91Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 92why, one step back92 /// Get the backtrace for this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 93why, one step back93 pub fn backtrace(&self) -> &Backtrace {Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 94–96why, one step back94 // NB: this unwrap can only fail if the underlying error's backtrace95 // method is nondeterministic, which would only happen in maliciously96 // constructed codeRename exception module to errorDavid Tolnaybefore adoption2000930
lines 97–100why, one step back97 self.inner98 .backtrace99 .as_ref()100 .or_else(|| self.inner.error().backtrace())Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 101why, one step back101 .expect("backtrace capture failed")Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 102–103why, one step back102 }103Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 104why, one step back104 /// An iterator of the chain of source errors contained by this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 105why, one step back105 ///Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 106why, one step back106 /// This iterator will visit every error in the cause chain of this errorWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 107–108why, one step back107 /// object, beginning with the error that this error object was created108 /// from.Rename Errors to ChainDavid Tolnaybefore adoptionf972193
lines 109–110why, one step back109 pub fn chain(&self) -> Chain {110 Chain {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 111–114why, one step back111 next: Some(self.inner.error()),112 }113 }114Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 115why, one step back115 /// Returns `true` if `E` is the type wrapped by this error object.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 116–119why, one step back116 pub fn is<E>(&self) -> bool117 where118 E: Display + Debug + Send + Sync + 'static,119 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 120–122why, one step back120 TypeId::of::<E>() == self.inner.type_id121 }122Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 123why, one step back123 /// Attempt to downcast the error object to a concrete type.Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 124why, one step back124 pub fn downcast<E>(self) -> Result<E, Self>Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 125–127why, one step back125 where126 E: Display + Debug + Send + Sync + 'static,127 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 128–139why, one step back128 if let Some(error) = self.downcast_ref::<E>() {129 unsafe {130 let error = ptr::read(error);131 drop(ptr::read(&self.inner));132 mem::forget(self);133 Ok(error)134 }135 } else {136 Err(self)137 }138 }139Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 140why, one step back140 /// Downcast this error object by reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 141–144why, one step back141 pub fn downcast_ref<E>(&self) -> Option<&E>142 where143 E: Display + Debug + Send + Sync + 'static,144 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 145why, one step back145 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 146why, one step back146 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 147–151why, one step back147 } else {148 None149 }150 }151Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 152why, one step back152 /// Downcast this error object by mutable reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 153–156why, one step back153 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>154 where155 E: Display + Debug + Send + Sync + 'static,156 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 157why, one step back157 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 158why, one step back158 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 159–164why, one step back159 } else {160 None161 }162 }163}164Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 165–168why, one step back165impl<E> From<E> for Error166where167 E: StdError + Send + Sync + 'static,168{Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 169why, one step back169 fn from(error: E) -> Self {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 170why, one step back170 Error::new(error)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 171–173why, one step back171 }172}173Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 174why, one step back174impl Deref for Error {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 175why, one step back175 type Target = dyn StdError + Send + Sync + 'static;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 176–180why, one step back176 fn deref(&self) -> &Self::Target {177 self.inner.error()178 }179}180Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 181why, one step back181impl DerefMut for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 182–186why, one step back182 fn deref_mut(&mut self) -> &mut Self::Target {183 self.inner.error_mut()184 }185}186Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 187why, one step back187impl Debug for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 188–190why, one step back188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {189 writeln!(f, "{}", self.inner.error())?;190Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 191why, one step back191 let mut errors = self.chain().skip(1).enumerate();Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 192–209why, one step back192193 if let Some((n, error)) = errors.next() {194 writeln!(f, "\ncaused by:")?;195 writeln!(f, "\t{}: {}", n, error)?;196 for (n, error) in errors {197 writeln!(f, "\t{}: {}", n, error)?;198 }199 }200201 let backtrace = self.backtrace();202203 match backtrace.status() {204 BacktraceStatus::Captured => {205 writeln!(f, "\n{}", backtrace)?;206 }207 BacktraceStatus::Disabled => {208 writeln!(209 f,Recommend RUST_LIB_BACKTRACE=1 variableDavid Tolnaybefore adoption71b360e
line 210why, one step back210 "\nbacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 211–219why, one step back211 )?;212 }213 _ => {}214 }215216 Ok(())217 }218}219Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 220why, one step back220impl Display for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 221–225why, one step back221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {222 write!(f, "{}", self.inner.error())223 }224}225Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 226–227why, one step back226unsafe impl Send for Error {}227unsafe impl Sync for Error {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 228why, one step back228Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 229why, one step back229impl Drop for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 230–236why, one step back230 fn drop(&mut self) {231 unsafe { ptr::drop_in_place(self.inner.error_mut()) }232 }233}234235// repr C to ensure that `E` remains in the final position236#[repr(C)]Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 237why, one step back237struct ErrorImpl<E> {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 238–251why, one step back238 vtable: *const (),239 type_id: TypeId,240 backtrace: Option<Backtrace>,241 error: E,242}243244// repr C to ensure that transmuting from trait objects is safe245#[repr(C)]246struct TraitObject {247 data: *const (),248 vtable: *const (),249}250251#[repr(transparent)]Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1
line 252why, one step back252struct MessageError<M>(M);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 253why, one step back253Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 254–257why, one step back254impl<M> Debug for MessageError<M>255where256 M: Display + Debug,257{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 258–262why, one step back258 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {259 Debug::fmt(&self.0, f)260 }261}262Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 263–266why, one step back263impl<M> Display for MessageError<M>264where265 M: Display + Debug,266{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 267–271why, one step back267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {268 Display::fmt(&self.0, f)269 }270}271Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
line 272why, one step back272impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 273why, one step back273Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 274why, one step back274impl ErrorImpl<()> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 275why, one step back275 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
lines 276–281why, one step back276 let object = TraitObject {277 data: &self.error,278 vtable: self.vtable,279 };280281 unsafe { mem::transmute::<TraitObject, &(dyn StdError + Send + Sync + 'static)>(object) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 282–283why, one step back282 }283Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 284why, one step back284 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
lines 285–289why, one step back285 let object = TraitObject {286 data: &mut self.error,287 vtable: self.vtable,288 };289Rename exception module to errorDavid Tolnaybefore adoption2000930
line 290why, one step back290 unsafe {Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742
line 291why, one step back291 mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 292–295why, one step back292 }293 }294}295Rename Errors to ChainDavid Tolnaybefore adoptionf972193
lines 296–297why, one step back296/// Iterator of a chain of source errors.297pub struct Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 298why, one step back298 next: Option<&'a (dyn StdError + 'static)>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 299–300why, one step back299}300Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 301why, one step back301impl<'a> Iterator for Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 302why, one step back302 type Item = &'a (dyn StdError + 'static);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 303–318why, one step back303304 fn next(&mut self) -> Option<Self::Item> {305 let next = self.next.take()?;306 self.next = next.source();307 Some(next)308 }309}310311#[cfg(test)]312mod repr_correctness {313 use super::*;314315 use std::marker::Unpin;316 use std::mem;317318 #[test]Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 319why, one step back319 fn size_of_error() {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 320why, one step back320 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 321–323why, one step back321 }322323 #[allow(dead_code)]Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 324why, one step back324 fn assert_error_autotraits()Rename exception module to errorDavid Tolnaybefore adoption2000930
line 325why, one step back325 whereRename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 326why, one step back326 Error: Unpin + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 327–335why, one step back327 {328 }329330 #[test]331 fn destructors_work() {332 use std::sync::*;333334 #[derive(Debug)]335 struct HasDrop(Box<Arc<Mutex<bool>>>);Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 336why, one step back336 impl StdError for HasDrop {}Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 337–351why, one step back337 impl Display for HasDrop {338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {339 write!(f, "does something")340 }341 }342 impl Drop for HasDrop {343 fn drop(&mut self) {344 let mut has_dropped = self.0.lock().unwrap();345 assert!(!*has_dropped);346 *has_dropped = true;347 }348 }349350 let has_dropped = Arc::new(Mutex::new(false));351Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 352why, one step back352 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 353–356why, one step back353354 assert!(*has_dropped.lock().unwrap());355 }356}