error.rs
This file
Path
src/error.rs
520 lines · 14.5 KiB · Rust
Last changed by
Capture backtraces earlierDavid Tolnaybefore adoptionc06155e
History of this fileTake it
Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101
line 1why, one step back1use crate::backtrace::Backtrace;Add context method to ErrorDavid Tolnaybefore adoption41fde4c
line 2why, one step back2use crate::context::ContextError;Rename exception module to errorDavid Tolnaybefore adoption2000930
line 3why, one step back3use std::any::TypeId;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///Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4
line 12why, one step back12/// `Error` works a lot like `Box<dyn std::error::Error>`, but with theseWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
line 13why, one step back13/// differences:Rename exception module to errorDavid Tolnaybefore adoption2000930
line 14why, one step back14///Touch up documentation on Error structDavid Tolnaybefore adoptiona8ce6e4
lines 15–19why, one step back15/// - `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.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 {Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
line 36why, one step back36 let backtrace = backtrace_if_absent!(error);Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 37–38why, one step back37 Error::from_std(error, backtrace)38 }Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 39why, one step back39Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
lines 40–45why, one step back40 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>();45Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
line 46why, one step back46 // Safety: passing typeid of the right type E.Format with rustfmt 2019-09-08David Tolnaybefore adoption2a9e5b6
line 47why, one step back47 unsafe { Error::construct(error, type_id, backtrace) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 48–49why, one step back48 }49Introduce safe from_std and matching from_adhocDavid Tolnaybefore adoption310dec9
line 50why, one step back50 pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
lines 51–53why, one step back51 where52 M: Display + Debug + Send + Sync + 'static,53 {Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 54–58why, one step back54 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.Format with rustfmt 2019-09-08David Tolnaybefore adoption2a9e5b6
line 59why, one step back59 unsafe { Error::construct(error, type_id, backtrace) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 60–61why, one step back60 }61Move Error::new backtrace capture to backtrace_if_absent macroDavid Tolnaybefore adoptioneaa819d
lines 62–63why, one step back62 // Takes backtrace as argument rather than capturing it here so that the63 // user sees one fewer layer of wrapping noise in the backtrace.Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 64–67why, one step back64 //65 // Unsafe because the type represented by type_id must have the same layout66 // as E or else we allow invalid downcasts.67 unsafe fn construct<E>(error: E, type_id: TypeId, backtrace: Option<Backtrace>) -> SelfRename exception module to errorDavid Tolnaybefore adoption2000930
line 68why, one step back68 whereImport std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 69why, one step back69 E: StdError + Send + Sync + 'static,Rename exception module to errorDavid Tolnaybefore adoption2000930
line 70why, one step back70 {Change Error::construct to unsafe fn because TypeId must be correctDavid Tolnaybefore adoptiondb2a298
lines 71–82why, one step back71 let vtable = &ErrorVTable {72 object: object_raw::<E>,73 object_mut: object_mut_raw::<E>,74 };75 let inner = Box::new(ErrorImpl {76 vtable,77 type_id,78 backtrace,79 error,80 });81 Error {82 inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),Rename exception module to errorDavid Tolnaybefore adoption2000930
line 83why, one step back83 }Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 84–86why, one step back84 }8586 /// Wrap the error value with additional context.Link to Context trait from Error::context methodDavid Tolnaybefore adoption61e587f
lines 87–90why, one step back87 ///88 /// For attaching context to a `Result` as it is propagated, the89 /// [`Context`][crate::Context] extension trait may be more convenient than90 /// this function.Explain the purpose of Error::contextDavid Tolnaybefore adoption896dd7a
lines 91–138why, one step back91 ///92 /// The primary reason to use `error.context(...)` instead of93 /// `result.context(...)` via the `Context` trait would be if the context94 /// needs to depend on some data held by the underlying error:95 ///96 /// ```97 /// # use std::fmt::{self, Debug, Display};98 /// #99 /// # type T = ();100 /// #101 /// # impl std::error::Error for ParseError {}102 /// # impl Debug for ParseError {103 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {104 /// # unimplemented!()105 /// # }106 /// # }107 /// # impl Display for ParseError {108 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {109 /// # unimplemented!()110 /// # }111 /// # }112 /// #113 /// use std::fs::File;114 /// use std::path::Path;115 ///116 /// struct ParseError {117 /// line: usize,118 /// column: usize,119 /// }120 ///121 /// fn parse_impl(file: File) -> Result<T, ParseError> {122 /// # const IGNORE: &str = stringify! {123 /// ...124 /// # };125 /// # unimplemented!()126 /// }127 ///128 /// pub fn parse(path: impl AsRef<Path>) -> anyhow::Result<T> {129 /// let file = File::open(&path)?;130 /// parse_impl(file).map_err(|error| {131 /// let context = format!(132 /// "only the first {} lines of {} are valid",133 /// error.line, path.as_ref().display(),134 /// );135 /// anyhow::Error::new(error).context(context)136 /// })137 /// }138 /// ```Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 139–142why, one step back139 pub fn context<C>(self, context: C) -> Self140 where141 C: Display + Send + Sync + 'static,142 {Change Error::from calls to Error::new to cut one level of noise from backtracesDavid Tolnaybefore adoption2c7d3ca
line 143why, one step back143 Error::new(ContextError {Add context method to ErrorDavid Tolnaybefore adoption41fde4c
lines 144–146why, one step back144 error: self,145 context,146 })Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 147–148why, one step back147 }148Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 149why, one step back149 /// Get the backtrace for this Error.Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 150–153why, one step back150 ///151 /// Backtraces are only available on the nightly channel. Tracking issue:152 /// [rust-lang/rust#53487][tracking].153 ///Mention env var in Error::backtrace documentationDavid Tolnaybefore adoption4119806
lines 154–158why, one step back154 /// In order for the backtrace to be meaningful, the environment variable155 /// `RUST_LIB_BACKTRACE=1` must be defined. Backtraces are somewhat156 /// expensive to capture in Rust, so we don't necessarily want to be157 /// capturing them all over the place all the time.158 ///Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 159–160why, one step back159 /// [tracking]: https://github.com/rust-lang/rust/issues/53487160 #[cfg(backtrace)]Rename exception module to errorDavid Tolnaybefore adoption2000930
line 161why, one step back161 pub fn backtrace(&self) -> &Backtrace {Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 162–164why, one step back162 // NB: this unwrap can only fail if the underlying error's backtrace163 // method is nondeterministic, which would only happen in maliciously164 // constructed codeRename exception module to errorDavid Tolnaybefore adoption2000930
lines 165–168why, one step back165 self.inner166 .backtrace167 .as_ref()168 .or_else(|| self.inner.error().backtrace())Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 169why, one step back169 .expect("backtrace capture failed")Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 170–171why, one step back170 }171Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 172why, one step back172 /// An iterator of the chain of source errors contained by this Error.Rename exception module to errorDavid Tolnaybefore adoption2000930
line 173why, one step back173 ///Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 174why, one step back174 /// This iterator will visit every error in the cause chain of this errorWrap comments to 80 columnsDavid Tolnaybefore adoption9745066
lines 175–176why, one step back175 /// object, beginning with the error that this error object was created176 /// from.Add example of Error::chainDavid Tolnaybefore adoptiond159b79
lines 177–192why, one step back177 ///178 /// # Example179 ///180 /// ```181 /// use anyhow::Error;182 /// use std::io;183 ///184 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {185 /// for cause in error.chain() {186 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {187 /// return Some(io_error.kind());188 /// }189 /// }190 /// None191 /// }192 /// ```Rename Errors to ChainDavid Tolnaybefore adoptionf972193
lines 193–194why, one step back193 pub fn chain(&self) -> Chain {194 Chain {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 195–198why, one step back195 next: Some(self.inner.error()),196 }197 }198Add Error::root_cause accessorDavid Tolnaybefore adoption1ea72bb
lines 199–212why, one step back199 /// The lowest level cause of this error — this error's cause's200 /// cause's cause etc.201 ///202 /// The root cause is the last error in the iterator produced by203 /// [`chain()`][Error::chain].204 pub fn root_cause(&self) -> &(dyn StdError + 'static) {205 let mut chain = self.chain();206 let mut root_cause = chain.next().unwrap();207 for cause in chain {208 root_cause = cause;209 }210 root_cause211 }212Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 213why, one step back213 /// Returns `true` if `E` is the type wrapped by this error object.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 214–217why, one step back214 pub fn is<E>(&self) -> bool215 where216 E: Display + Debug + Send + Sync + 'static,217 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 218–220why, one step back218 TypeId::of::<E>() == self.inner.type_id219 }220Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 221why, one step back221 /// Attempt to downcast the error object to a concrete type.Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 222why, one step back222 pub fn downcast<E>(self) -> Result<E, Self>Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 223–225why, one step back223 where224 E: Display + Debug + Send + Sync + 'static,225 {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 226–237why, one step back226 if let Some(error) = self.downcast_ref::<E>() {227 unsafe {228 let error = ptr::read(error);229 drop(ptr::read(&self.inner));230 mem::forget(self);231 Ok(error)232 }233 } else {234 Err(self)235 }236 }237Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 238why, one step back238 /// Downcast this error object by reference.Add example to Error::downcast_refDavid Tolnaybefore adoption0c21b7a
lines 239–273why, one step back239 ///240 /// # Example241 ///242 /// ```243 /// # use anyhow::anyhow;244 /// # use std::fmt::{self, Display};245 /// # use std::task::Poll;246 /// #247 /// # #[derive(Debug)]248 /// # enum DataStoreError {249 /// # Censored(()),250 /// # }251 /// #252 /// # impl Display for DataStoreError {253 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {254 /// # unimplemented!()255 /// # }256 /// # }257 /// #258 /// # impl std::error::Error for DataStoreError {}259 /// #260 /// # const REDACTED_CONTENT: () = ();261 /// #262 /// # let error = anyhow!("...");263 /// # let root_cause = &error;264 /// #265 /// # let ret =266 /// // If the error was caused by redaction, then return a tombstone instead267 /// // of the content.268 /// match root_cause.downcast_ref::<DataStoreError>() {269 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),270 /// None => Err(error),271 /// }272 /// # ;273 /// ```Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 274–277why, one step back274 pub fn downcast_ref<E>(&self) -> Option<&E>275 where276 E: Display + Debug + Send + Sync + 'static,277 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 278why, one step back278 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 279why, one step back279 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 280–284why, one step back280 } else {281 None282 }283 }284Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 285why, one step back285 /// Downcast this error object by mutable reference.Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 286–289why, one step back286 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>287 where288 E: Display + Debug + Send + Sync + 'static,289 {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 290why, one step back290 if self.is::<E>() {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 291why, one step back291 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn StdError as *mut E)) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 292–296why, one step back292 } else {293 None294 }295 }296}Remove use of attributes on function parametersDavid Tolnaybefore adoptiona2d7e2f
line 297why, one step back297Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 298–301why, one step back298impl<E> From<E> for Error299where300 E: StdError + Send + Sync + 'static,301{Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337
line 302why, one step back302 fn from(error: E) -> Self {Capture backtraces earlierDavid Tolnaybefore adoptionc06155e
lines 303–304why, one step back303 let backtrace = backtrace_if_absent!(error);304 Error::from_std(error, backtrace)Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 305–307why, one step back305 }306}307Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 308why, one step back308impl Deref for Error {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 309why, one step back309 type Target = dyn StdError + Send + Sync + 'static;Remove as_dyn_error methods from ErrorDavid Tolnaybefore adoption73c7283
line 310why, one step back310Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 311–315why, one step back311 fn deref(&self) -> &Self::Target {312 self.inner.error()313 }314}315Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 316why, one step back316impl DerefMut for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 317–321why, one step back317 fn deref_mut(&mut self) -> &mut Self::Target {318 self.inner.error_mut()319 }320}321Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 322why, one step back322impl Debug for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 323–325why, one step back323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {324 writeln!(f, "{}", self.inner.error())?;325Omit '0:' if only one causeDavid Tolnaybefore adoptionb0c8c75
line 326why, one step back326 let mut chain = self.chain().skip(1).enumerate().peekable();Touch up Debug impl for ErrorDavid Tolnaybefore adoption3cd7273
line 327why, one step back327 if let Some((n, error)) = chain.next() {Omit '0:' if only one causeDavid Tolnaybefore adoptionb0c8c75
lines 328–332why, one step back328 write!(f, "\nCaused by:\n ")?;329 if chain.peek().is_some() {330 write!(f, "{}: ", n)?;331 }332 writeln!(f, "{}", error)?;Touch up Debug impl for ErrorDavid Tolnaybefore adoption3cd7273
line 333why, one step back333 for (n, error) in chain {Indent causes in Debug representation with spacesDavid Tolnaybefore adoptionad275d5
line 334why, one step back334 writeln!(f, " {}: {}", n, error)?;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 335–337why, one step back335 }336 }337Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 338–339why, one step back338 #[cfg(backtrace)]339 {Move backtrace capture to backtrace module and macroDavid Tolnaybefore adoptionebd9101
lines 340–341why, one step back340 use std::backtrace::BacktraceStatus;341Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 342–349why, one step back342 let backtrace = self.backtrace();343 match backtrace.status() {344 BacktraceStatus::Captured => {345 writeln!(f, "\n{}", backtrace)?;346 }347 BacktraceStatus::Disabled => {348 writeln!(349 f,Capitalize lines of Debug representationDavid Tolnaybefore adoptiona97f8dc
line 350why, one step back350 "\nBacktrace disabled; run with RUST_LIB_BACKTRACE=1 environment variable to display a backtrace"Detect nightly and only expose backtrace if availableDavid Tolnaybefore adoption270ea5e
lines 351–353why, one step back351 )?;352 }353 _ => {}Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 354–360why, one step back354 }355 }356357 Ok(())358 }359}360Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 361why, one step back361impl Display for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 362–366why, one step back362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {363 write!(f, "{}", self.inner.error())364 }365}366Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
lines 367–368why, one step back367unsafe impl Send for Error {}368unsafe impl Sync for Error {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 369why, one step back369Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 370why, one step back370impl Drop for Error {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 371–375why, one step back371 fn drop(&mut self) {372 unsafe { ptr::drop_in_place(self.inner.error_mut()) }373 }374}375Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 376why, one step back376struct ErrorVTable {Rename source to object in vtableDavid Tolnaybefore adoption03ef684
lines 377–378why, one step back377 object: unsafe fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),378 object_mut: unsafe fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 379–380why, one step back379}380Rename source to object in vtableDavid Tolnaybefore adoption03ef684
line 381why, one step back381unsafe fn object_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 382–387why, one step back382where383 E: StdError + Send + Sync + 'static,384{385 e as *const E386}387Rename source to object in vtableDavid Tolnaybefore adoption03ef684
line 388why, one step back388unsafe fn object_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
lines 389–394why, one step back389where390 E: StdError + Send + Sync + 'static,391{392 e as *mut E393}394Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 395–396why, one step back395// repr C to ensure that `E` remains in the final position396#[repr(C)]Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 397why, one step back397struct ErrorImpl<E> {Merge pull request #5 from johnschug/masterDavid Tolnaybefore adoption8220e0a
line 398why, one step back398 vtable: &'static ErrorVTable,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 399–404why, one step back399 type_id: TypeId,400 backtrace: Option<Backtrace>,401 error: E,402}403404#[repr(transparent)]Remove trait bounds from MessageError structDavid Tolnaybefore adoptioneac05d1
line 405why, one step back405struct MessageError<M>(M);Rename exception module to errorDavid Tolnaybefore adoption2000930
line 406why, one step back406Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 407–410why, one step back407impl<M> Debug for MessageError<M>408where409 M: Display + Debug,410{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 411–415why, one step back411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {412 Debug::fmt(&self.0, f)413 }414}415Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
lines 416–419why, one step back416impl<M> Display for MessageError<M>417where418 M: Display + Debug,419{Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 420–424why, one step back420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {421 Display::fmt(&self.0, f)422 }423}424Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851
line 425why, one step back425impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}Rename exception module to errorDavid Tolnaybefore adoption2000930
line 426why, one step back426Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84
line 427why, one step back427impl ErrorImpl<()> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 428why, one step back428 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {Rename source to object in vtableDavid Tolnaybefore adoption03ef684
line 429why, one step back429 unsafe { &*(self.vtable.object)(&self.error) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 430–431why, one step back430 }431Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 432why, one step back432 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {Rename source to object in vtableDavid Tolnaybefore adoption03ef684
line 433why, one step back433 unsafe { &mut *(self.vtable.object_mut)(&mut self.error) }Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 434–436why, one step back434 }435}436Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 437why, one step back437/// Iterator of a chain of source errors.Add example to Chain iteratorDavid Tolnaybefore adoptionfeb9f33
lines 438–455why, one step back438///439/// This type is the iterator returned by [`Error::chain`].440///441/// # Example442///443/// ```444/// use anyhow::Error;445/// use std::io;446///447/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {448/// for cause in error.chain() {449/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {450/// return Some(io_error.kind());451/// }452/// }453/// None454/// }455/// ```Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 456why, one step back456pub struct Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 457why, one step back457 next: Option<&'a (dyn StdError + 'static)>,Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 458–459why, one step back458}459Rename Errors to ChainDavid Tolnaybefore adoptionf972193
line 460why, one step back460impl<'a> Iterator for Chain<'a> {Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190
line 461why, one step back461 type Item = &'a (dyn StdError + 'static);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 462–474why, one step back462463 fn next(&mut self) -> Option<Self::Item> {464 let next = self.next.take()?;465 self.next = next.source();466 Some(next)467 }468}469470#[cfg(test)]471mod repr_correctness {472 use super::*;473 use std::marker::Unpin;474 use std::mem;Replace Mutex<bool> with AtomicBoolDavid Tolnaybefore adoption794ba39
lines 475–477why, one step back475 use std::sync::atomic::AtomicBool;476 use std::sync::atomic::Ordering::SeqCst;477 use std::sync::Arc;Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 478–479why, one step back478479 #[test]Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c
line 480why, one step back480 fn size_of_error() {Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc
line 481why, one step back481 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 482–483why, one step back482 }483Simplify autotraits testDavid Tolnaybefore adoptionb0e25c5
lines 484–487why, one step back484 #[test]485 fn error_autotraits() {486 fn assert<E: Unpin + Send + Sync + 'static>() {}487 assert::<Error>();Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 488–490why, one step back488 }489490 #[test]Improve naming in Drop testDavid Tolnaybefore adoption04931ad
line 491why, one step back491 fn drop_works() {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 492why, one step back492 #[derive(Debug)]Improve naming in Drop testDavid Tolnaybefore adoption04931ad
lines 493–499why, one step back493 struct DetectDrop {494 has_dropped: Arc<AtomicBool>,495 }496497 impl StdError for DetectDrop {}498499 impl Display for DetectDrop {Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 500–503why, one step back500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {501 write!(f, "does something")502 }503 }Improve naming in Drop testDavid Tolnaybefore adoption04931ad
lines 504–505why, one step back504505 impl Drop for DetectDrop {Rename exception module to errorDavid Tolnaybefore adoption2000930
line 506why, one step back506 fn drop(&mut self) {Improve naming in Drop testDavid Tolnaybefore adoption04931ad
lines 507–508why, one step back507 let already_dropped = self.has_dropped.swap(true, SeqCst);508 assert!(!already_dropped);Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 509–511why, one step back509 }510 }511Replace Mutex<bool> with AtomicBoolDavid Tolnaybefore adoption794ba39
line 512why, one step back512 let has_dropped = Arc::new(AtomicBool::new(false));Rename exception module to errorDavid Tolnaybefore adoption2000930
line 513why, one step back513Change Error::from calls to Error::new to cut one level of noise from backtracesDavid Tolnaybefore adoption2c7d3ca
line 514why, one step back514 drop(Error::new(DetectDrop {Improve naming in Drop testDavid Tolnaybefore adoption04931ad
lines 515–516why, one step back515 has_dropped: has_dropped.clone(),516 }));Rename exception module to errorDavid Tolnaybefore adoption2000930
line 517why, one step back517Replace Mutex<bool> with AtomicBoolDavid Tolnaybefore adoption794ba39
line 518why, one step back518 assert!(has_dropped.load(SeqCst));Rename exception module to errorDavid Tolnaybefore adoption2000930
lines 519–520why, one step back519 }520}