1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
//! Helpers for bundling context with errors and later extracting said context thru `dyn Error` //! trait objects. //! //! The primary purpose of this crate is to pass context to error reporters through `dyn Error` //! trait objects. This is useful for information that may need to be captured by leaf errors but //! which doesn't belong in any single error's message. Backtraces, http status codes, and help //! messages are all examples of context that one might wish to pass directly to an error reporter //! rather than printing in the chain of errors. //! //! ## Setup //! //! ```toml //! [dependencies] //! extracterr = "0.1" //! ``` //! //! ## TLDR Example //! //! ```rust //! use backtrace::Backtrace; //! use std::error::Error; //! use extracterr::{Bundle, Bundled, Extract}; //! //! #[derive(Debug, thiserror::Error)] //! #[error("Example Error")] //! struct ExampleError; //! //! let error = ExampleError; //! //! // Capture a backtrace via `Default` and `From` //! let error: Bundled<_, Backtrace> = error.into(); //! //! // Convert it to a trait object to throw away type information //! let error: Box<dyn Error + Send + Sync + 'static> = error.into(); //! //! // first error in chain is the unerased version of the error `Bundled<ExampleError, Backtrace>` //! assert!(error.downcast_ref::<Bundled<ExampleError, Backtrace>>().is_some()); //! assert_eq!("Example Error", error.to_string()); //! assert!(error.extract::<Backtrace>().is_none()); //! //! // Move to the next error in the chain //! let error = error.source().unwrap(); //! //! // The second error in the chain is the erased version `Bundled<Erased, Backtrace>` which now //! // works with downcasting, letting us access the bundled context //! let backtrace = error.extract::<Backtrace>(); //! assert!(backtrace.is_some()); //! //! // The Display / Debug impls of the fake error that contains the bundled context print the //! // context's type_name //! assert_eq!(error.to_string(), std::any::type_name::<Backtrace>()); //! ``` //! //! ## Details //! //! The main type provided by this library is the `Bundled` type, which bundles an error and a //! context type into a new error. This type can be constructed either via `From+Default` or //! [`Bundle`], for more details check out the docs on [`Bundled`]. //! //! This type works best with the error kind pattern, as seen in `std::io::Error`: //! //! ```rust //! use backtrace::Backtrace; //! use extracterr::{Bundle, Bundled}; //! //! #[derive(Debug, thiserror::Error)] //! #[error(transparent)] //! struct Error { //! kind: Bundled<Kind, Backtrace>, //! } //! //! #[derive(Debug, thiserror::Error, Clone, Copy)] //! enum Kind { //! #[error("could not enqueue item")] //! Queue, //! #[error("could not dequeue item")] //! Dequeue //! } //! //! impl Error { //! fn kind(&self) -> Kind { //! *self.kind.inner() //! } //! } //! //! impl From<Kind> for Error { //! fn from(kind: Kind) -> Self { //! Self { kind: Bundled::from(kind) } //! } //! } //! //! impl From<Bundled<Kind, Backtrace>> for Error { //! fn from(kind: Bundled<Kind, Backtrace>) -> Self { //! Self { kind } //! } //! } //! //! fn queue() -> Result<(), Error> { //! Err(Kind::Queue)? //! } //! //! fn dequeue() -> Result<(), Error> { //! Err(Kind::Dequeue).bundle(Backtrace::new())? //! } //! //! use extracterr::Extract; //! //! let error = dequeue().unwrap_err(); //! //! // Convert it to a trait object to throw away type information //! let error: Box<dyn std::error::Error + Send + Sync + 'static> = error.into(); //! //! assert!(error.downcast_ref::<Error>().is_some()); //! assert_eq!("could not dequeue item", error.to_string()); //! assert!(error.extract::<Backtrace>().is_none()); //! //! // Move to the next error in the chain //! let error = error.source().unwrap(); //! //! let backtrace = error.extract::<Backtrace>(); //! assert!(backtrace.is_some()); //! ``` //! //! Once context has been bundled into a chain of errors it can then be extracted back out via the //! [`Extract`] trait. Check out the source code of [`stable-eyre`] for a simple example of //! idiomatic usage of `Extract` in an error reporter. //! //! [`Bundle`]: trait.Bundle.html //! [`Bundled`]: struct.Bundled.html //! [`Extract`]: trait.Extract.html //! [`stable-eyre`]: https://github.com/yaahc/stable-eyre #![doc(html_root_url = "https://docs.rs/extracterr/0.1.1")] #![warn( missing_debug_implementations, missing_docs, missing_doc_code_examples, rust_2018_idioms, unreachable_pub, bad_style, const_err, dead_code, improper_ctypes, non_shorthand_field_patterns, no_mangle_generic_items, overflowing_literals, path_statements, patterns_in_fns_without_body, private_in_public, unconditional_recursion, unused, unused_allocation, unused_comparisons, unused_parens, while_true )] use std::error::Error; use std::fmt::{self, Debug, Display}; struct Erased; /// An Error bundled with a Context can then later be extracted from a chain of dyn Errors. /// /// # Usage /// /// This type has two primary methods of construction, `From` and [`Bundle`]. The first method of /// construction, the `From` trait, only works when the type you're bundling with the error /// implements `Default`. This is useful for types like `Backtrace`s where the context you care /// about is implicitly captured just by constructing the type, or for types that have a reasonable /// default like HttpStatusCodes defaulting to 500. /// /// ``` /// use extracterr::Bundled; /// /// #[derive(Debug, thiserror::Error)] /// #[error("just an example error")] /// struct ExampleError; /// /// struct StatusCode(u32); /// /// impl Default for StatusCode { /// fn default() -> Self { /// Self(500) /// } /// } /// /// /// fn foo() -> Result<(), Bundled<ExampleError, StatusCode>> { /// Err(ExampleError)? /// } /// ``` /// /// The second method of construction, the [`Bundle`] trait, lets you attach context to errors /// manually. This is useful for types that don't implement `Default` or types where you only /// occasionally want to override the defaults. /// /// ``` /// use extracterr::{Bundled, Bundle}; /// /// #[derive(Debug, thiserror::Error)] /// #[error("just an example error")] /// struct ExampleError; /// /// struct StatusCode(u32); /// /// fn foo() -> Result<(), Bundled<ExampleError, StatusCode>> { /// Err(ExampleError).bundle(StatusCode(404))? /// } /// ``` /// /// Once context has been bundled with an error it can then be extracted by an error reporter with /// the [`Extract`] trait. /// /// [`Bundle`]: trait.Bundle.html /// [`Bundled`]: struct.Bundled.html /// [`Extract`]: trait.Extract.html pub struct Bundled<E, C: 'static> { inner: ErrorImpl<E, C>, } impl<E, C: 'static> Bundled<E, C> { fn bundle(error: E, context: C) -> Bundled<E, C> where E: Error + Send + Sync + 'static, { // # SAFETY // // This function + the repr(C) on the ErrorImpl make the type erasure throughout the rest // of this struct's methods safe. This saves a function pointer that is parameterized on the Error type // being stored inside the ErrorImpl. This lets the object_ref function safely cast a type // erased `ErrorImpl` back to its original type, which is needed in order to forward our // error/display/debug impls to the internal error type from the type erased error type. // // The repr(C) is necessary to ensure that the struct is layed out in the order we // specified it so that we can safely access the vtable and spantrace fields thru a type // erased pointer to the original object. let vtable = &ErrorVTable { object_ref: object_ref::<E, C>, }; Self { inner: ErrorImpl { vtable, context, error, }, } } /// Returns a reference to the inner error pub fn inner(&self) -> &E { &self.inner.error } } impl<E, C> From<E> for Bundled<E, C> where E: Error + Send + Sync + 'static, C: Default, { fn from(error: E) -> Self { Self::bundle(error, C::default()) } } #[repr(C)] struct ErrorImpl<E, C: 'static> { vtable: &'static ErrorVTable<C>, context: C, // NOTE: Don't use directly. Use only through vtable. Erased type may have // different alignment. error: E, } impl<C> ErrorImpl<Erased, C> { pub(crate) fn error(&self) -> &(dyn Error + Send + Sync + 'static) { // # SAFETY // // this function is used to cast a type-erased pointer to a pointer to error's // original type. the `ErrorImpl::error` method, which calls this function, requires that // the type this function casts to be the original erased type of the error; failure to // uphold this is UB. since the `From` impl is parameterized over the original error type, // the function pointer we construct here will also retain the original type. therefore, // when this is consumed by the `error` method, it will be safe to call. unsafe { &*(self.vtable.object_ref)(self) } } } struct ErrorVTable<C: 'static> { object_ref: unsafe fn(&ErrorImpl<Erased, C>) -> &(dyn Error + Send + Sync + 'static), } // # SAFETY // // This function must be parameterized on the type E of the original error that is being stored // inside of the `ErrorImpl`. When it is parameterized by the correct type, it safely // casts the erased `ErrorImpl` pointer type back to the original pointer type. unsafe fn object_ref<E, C>(e: &ErrorImpl<Erased, C>) -> &(dyn Error + Send + Sync + 'static) where E: Error + Send + Sync + 'static, { // Attach E's native Error vtable onto a pointer to e.error. &(*(e as *const ErrorImpl<Erased, C> as *const ErrorImpl<E, C>)).error } impl<E, C> Error for Bundled<E, C> where E: std::error::Error + 'static, { // # SAFETY // // This function is safe so long as all functions on `ErrorImpl<Erased>` uphold the invariant // that the wrapped error is only ever accessed by the `error` method. This method uses the // function in the vtable to safely convert the pointer type back to the original type, and // then returns the reference to the erased error. // // This function is necessary for the `downcast_ref` in `ExtractSpanTrace` to work, because it // needs a concrete type to downcast to and we cannot downcast to ErrorImpls parameterized on // errors defined in other crates. By erasing the type here we can always cast back to the // Erased version of the ErrorImpl pointer, and still access the internal error type safely // through the vtable. fn source<'a>(&'a self) -> Option<&'a (dyn Error + 'static)> { let erased = unsafe { &*(&self.inner as *const ErrorImpl<E, C> as *const ErrorImpl<Erased, C>) }; Some(erased) } } impl<E, C> Debug for Bundled<E, C> where E: std::error::Error, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt(&self.inner.error, f) } } impl<E, C> Display for Bundled<E, C> where E: std::error::Error, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&self.inner.error, f) } } impl<C> Error for ErrorImpl<Erased, C> { fn source(&self) -> Option<&(dyn Error + 'static)> { self.error().source() } } impl<C> Debug for ErrorImpl<Erased, C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(std::any::type_name::<C>(), f) } } impl<C> Display for ErrorImpl<Erased, C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(std::any::type_name::<C>(), f) } } /// Extension trait for bundling context with errors through `Result` types pub trait Bundle<T, C> { /// The output error type after bundling with the provided context type Bundled; /// ``` /// use extracterr::{Bundle, Bundled}; /// /// struct Dummy(i32); /// /// fn do_thing() -> Result<(), std::io::Error> { /// // ... /// # Ok(()) /// } /// /// let r = do_thing().bundle(Dummy(0)); //: Result<(), Bundled<std::io::Error, Dummy>> /// ``` fn bundle(self, context: C) -> Result<T, Self::Bundled>; } impl<T, E, C> Bundle<T, C> for Result<T, E> where E: Error + Send + Sync + 'static, C: 'static, { type Bundled = Bundled<E, C>; fn bundle(self, context: C) -> Result<T, Self::Bundled> { self.map_err(|error| Bundled::bundle(error, context)) } } /// Extension trait for extracting references to bundled context from `dyn Error` trait objects pub trait Extract { /// # Example /// /// ```rust /// use std::error::Error; /// use backtrace::Backtrace; /// use extracterr::{Bundled, Extract}; /// /// fn report(error: &(dyn Error + 'static)) { /// let mut source = Some(error); /// let mut ind = 0; /// let mut backtrace = None; /// /// while let Some(error) = source { /// source = error.source(); /// /// if let Some(bt) = error.extract::<Backtrace>() { /// backtrace = Some(bt); /// } else { /// println!("{}: {}", ind, error); /// ind += 1; /// } /// } /// /// if let Some(backtrace) = backtrace { /// println!("\nBacktrace:\n{:?}", backtrace) /// } /// } /// ``` fn extract<C>(&self) -> Option<&C> where C: 'static; } impl Extract for dyn Error + 'static { fn extract<C>(&self) -> Option<&C> where C: 'static, { self.downcast_ref::<ErrorImpl<Erased, C>>() .map(|inner| &inner.context) } } impl Extract for dyn Error + Send + Sync + 'static { fn extract<C>(&self) -> Option<&C> where C: 'static, { self.downcast_ref::<ErrorImpl<Erased, C>>() .map(|inner| &inner.context) } }