Skip to content
Myr

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 file

Take it

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

line 1why, one step back
1use crate::context::ContextError;

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 2–3why, one step back
2use std::any::TypeId;
3use std::backtrace::{Backtrace, BacktraceStatus};

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 4why, one step back
4use std::error::Error as StdError;

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 5–9why, one step back
5use std::fmt::{self, Debug, Display};
6use std::mem;7use std::ops::{Deref, DerefMut};8use std::ptr;9

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 10why, one step back
10/// The `Error` type, a wrapper around a dynamic error type.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 11why, one step back
11///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 12–13why, one step back
12/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these
13/// differences:

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 14why, one step back
14///

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 15–16why, one step back
15/// - `Error` requires that the error is `Send`, `Sync`, and `'static`
16/// - `Error` guarantees that a backtrace will exist, even if the error type

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 17why, one step back
17/// did not provide one

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 18why, one step back
18/// - `Error` is represented as a narrow pointer - exactly one word in size,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 19why, one step back
19/// instead of two.

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 20why, one step back
20pub struct Error {

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 21why, one step back
21 inner: Box<ErrorImpl<()>>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 22–23why, one step back
22}
23

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 24why, one step back
24impl Error {

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 25why, one step back
25 /// Create a new error object from any error type.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 26why, one step back
26 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 27–28why, one step back
27 /// 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 back
29 ///

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 30–31why, one step back
30 /// If the error type does not provide a backtrace, a backtrace will be
31 /// created here to ensure that a backtrace exists.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 32why, one step back
32 pub fn new<E>(error: E) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 33why, one step back
33 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 34why, one step back
34 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 35why, one step back
35 {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 36why, one step back
36 Error::construct(error, TypeId::of::<E>())

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 37–39why, one step back
37 }
3839 #[doc(hidden)]

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 40why, one step back
40 pub fn new_adhoc<M>(message: M) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 41–43why, one step back
41 where
42 M: Display + Debug + Send + Sync + 'static,43 {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 44why, one step back
44 Error::construct(MessageError(message), TypeId::of::<M>())

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 45–46why, one step back
45 }
46

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 47why, one step back
47 fn construct<E>(error: E, type_id: TypeId) -> Self

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 48why, one step back
48 where

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 49why, one step back
49 E: StdError + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 50why, one step back
50 {

Shrink backtrace capture unsafe blockDavid Tolnaybefore adoption3adc96a

lines 51–55why, one step back
51 let backtrace = match error.backtrace() {
52 Some(_) => None,53 None => Some(Backtrace::capture()),54 };55

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 56why, one step back
56 unsafe {

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

line 57why, one step back
57 let obj = mem::transmute::<&dyn StdError, TraitObject>(&error);

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 58why, one step back
58 let vtable = obj.vtable;

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

line 59why, one step back
59 let inner = Box::new(ErrorImpl {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 60–63why, one step back
60 vtable,
61 type_id,62 backtrace,63 error,

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

line 64why, one step back
64 });

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 65why, one step back
65 Error {

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

line 66why, one step back
66 inner: mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner),

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 67–68why, one step back
67 }
68 }

Add context method to ErrorDavid Tolnaybefore adoption41fde4c

lines 69–79why, one step back
69 }
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 back
80 }
81

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 82why, one step back
82 /// View this error object as the underlying error.

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

line 83why, one step back
83 pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 84–86why, one step back
84 &**self
85 }86

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 87why, one step back
87 /// View this error object as the underlying error, mutably.

Rename as_error to as_dyn_errorDavid Tolnaybefore adoption895d383

line 88why, one step back
88 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 back
89 &mut **self
90 }91

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 92why, one step back
92 /// Get the backtrace for this Error.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 93why, one step back
93 pub fn backtrace(&self) -> &Backtrace {

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 94–96why, one step back
94 // NB: this unwrap can only fail if the underlying error's backtrace
95 // method is nondeterministic, which would only happen in maliciously96 // constructed code

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 97–100why, one step back
97 self.inner
98 .backtrace99 .as_ref()100 .or_else(|| self.inner.error().backtrace())

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 101why, one step back
101 .expect("backtrace capture failed")

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 102–103why, one step back
102 }
103

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 104why, one step back
104 /// An iterator of the chain of source errors contained by this Error.

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 105why, one step back
105 ///

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 106why, one step back
106 /// This iterator will visit every error in the cause chain of this error

Wrap comments to 80 columnsDavid Tolnaybefore adoption9745066

lines 107–108why, one step back
107 /// object, beginning with the error that this error object was created
108 /// from.

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

lines 109–110why, one step back
109 pub fn chain(&self) -> Chain {
110 Chain {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 111–114why, one step back
111 next: Some(self.inner.error()),
112 }113 }114

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 115why, one step back
115 /// 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 back
116 pub fn is<E>(&self) -> bool
117 where118 E: Display + Debug + Send + Sync + 'static,119 {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 120–122why, one step back
120 TypeId::of::<E>() == self.inner.type_id
121 }122

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 123why, one step back
123 /// Attempt to downcast the error object to a concrete type.

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 124why, one step back
124 pub fn downcast<E>(self) -> Result<E, Self>

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 125–127why, one step back
125 where
126 E: Display + Debug + Send + Sync + 'static,127 {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 128–139why, one step back
128 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 }139

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 140why, one step back
140 /// Downcast this error object by reference.

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 141–144why, one step back
141 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 back
145 if self.is::<E>() {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 146why, one step back
146 unsafe { Some(&*(self.inner.error() as *const dyn StdError as *const E)) }

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 147–151why, one step back
147 } else {
148 None149 }150 }151

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 152why, one step back
152 /// Downcast this error object by mutable reference.

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 153–156why, one step back
153 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 back
157 if self.is::<E>() {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 158why, one step back
158 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 back
159 } else {
160 None161 }162 }163}164

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 165–168why, one step back
165impl<E> From<E> for Error
166where167 E: StdError + Send + Sync + 'static,168{

Use Self in signatures of Error constructorsDavid Tolnaybefore adoption1ee4337

line 169why, one step back
169 fn from(error: E) -> Self {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 170why, one step back
170 Error::new(error)

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 171–173why, one step back
171 }
172}173

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 174why, one step back
174impl Deref for Error {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 175why, one step back
175 type Target = dyn StdError + Send + Sync + 'static;

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 176–180why, one step back
176 fn deref(&self) -> &Self::Target {
177 self.inner.error()178 }179}180

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 181why, one step back
181impl DerefMut for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 182–186why, one step back
182 fn deref_mut(&mut self) -> &mut Self::Target {
183 self.inner.error_mut()184 }185}186

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 187why, one step back
187impl Debug for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 188–190why, one step back
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 writeln!(f, "{}", self.inner.error())?;190

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 191why, one step back
191 let mut errors = self.chain().skip(1).enumerate();

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 192–209why, one step back
192
193 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 back
210 "\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 back
211 )?;
212 }213 _ => {}214 }215216 Ok(())217 }218}219

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 220why, one step back
220impl Display for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 221–225why, one step back
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222 write!(f, "{}", self.inner.error())223 }224}225

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

lines 226–227why, one step back
226unsafe impl Send for Error {}
227unsafe impl Sync for Error {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 228why, one step back
228

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 229why, one step back
229impl Drop for Error {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 230–236why, one step back
230 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 back
237struct ErrorImpl<E> {

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 238–251why, one step back
238 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 back
252struct MessageError<M>(M);

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 253why, one step back
253

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 254–257why, one step back
254impl<M> Debug for MessageError<M>
255where256 M: Display + Debug,257{

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 258–262why, one step back
258 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
259 Debug::fmt(&self.0, f)260 }261}262

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

lines 263–266why, one step back
263impl<M> Display for MessageError<M>
264where265 M: Display + Debug,266{

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 267–271why, one step back
267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
268 Display::fmt(&self.0, f)269 }270}271

Move trait bounds to where-clausesDavid Tolnaybefore adoption7dcc851

line 272why, one step back
272impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 273why, one step back
273

Rename InnerException to ErrorImplDavid Tolnaybefore adoption68dcc84

line 274why, one step back
274impl ErrorImpl<()> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 275why, one step back
275 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

lines 276–281why, one step back
276 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 back
282 }
283

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 284why, one step back
284 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

lines 285–289why, one step back
285 let object = TraitObject {
286 data: &mut self.error,287 vtable: self.vtable,288 };289

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 290why, one step back
290 unsafe {

Specify generic params on every transmuteDavid Tolnaybefore adoption46ad742

line 291why, one step back
291 mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 292–295why, one step back
292 }
293 }294}295

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

lines 296–297why, one step back
296/// Iterator of a chain of source errors.
297pub struct Chain<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 298why, one step back
298 next: Option<&'a (dyn StdError + 'static)>,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 299–300why, one step back
299}
300

Rename Errors to ChainDavid Tolnaybefore adoptionf972193

line 301why, one step back
301impl<'a> Iterator for Chain<'a> {

Import std::error::Error as StdErrorDavid Tolnaybefore adoption7afc190

line 302why, one step back
302 type Item = &'a (dyn StdError + 'static);

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 303–318why, one step back
303
304 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 back
319 fn size_of_error() {

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 320why, one step back
320 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 321–323why, one step back
321 }
322323 #[allow(dead_code)]

Change all remaining exception related wordingDavid Tolnaybefore adoption94d944c

line 324why, one step back
324 fn assert_error_autotraits()

Rename exception module to errorDavid Tolnaybefore adoption2000930

line 325why, one step back
325 where

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 326why, one step back
326 Error: Unpin + Send + Sync + 'static,

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 327–335why, one step back
327 {
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 back
336 impl StdError for HasDrop {}

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 337–351why, one step back
337 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));351

Rename Exception to ErrorDavid Tolnaybefore adoption5535ffc

line 352why, one step back
352 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));

Rename exception module to errorDavid Tolnaybefore adoption2000930

lines 353–356why, one step back
353
354 assert!(*has_dropped.lock().unwrap());355 }356}