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
#![no_std] #[cfg(feature = "std")] extern crate std; use core::fmt::*; #[cfg(feature = "std")] pub use std::error::Error; #[cfg(not(feature = "std"))] /// `Error` is a trait representing the basic expectations for error values, /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe /// themselves through the [`Display`] and [`Debug`] traits, and may provide /// cause chain information: /// /// The [`source`] method is generally used when errors cross "abstraction /// boundaries". If one module must report an error that is caused by an error /// from a lower-level module, it can allow access to that error via the /// [`source`] method. This makes it possible for the high-level module to /// provide its own errors while also revealing some of the implementation for /// debugging via [`source`] chains. /// /// [`source`]: trait.Error.html#method.source pub trait Error: Debug + Display { /// The lower-level source of this error, if any. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::fmt; /// /// #[derive(Debug)] /// struct SuperError { /// side: SuperErrorSideKick, /// } /// /// impl fmt::Display for SuperError { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// write!(f, "SuperError is here!") /// } /// } /// /// impl Error for SuperError { /// fn source(&self) -> Option<&(dyn Error + 'static)> { /// Some(&self.side) /// } /// } /// /// #[derive(Debug)] /// struct SuperErrorSideKick; /// /// impl fmt::Display for SuperErrorSideKick { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// write!(f, "SuperErrorSideKick is here!") /// } /// } /// /// impl Error for SuperErrorSideKick {} /// /// fn get_super_error() -> Result<(), SuperError> { /// Err(SuperError { side: SuperErrorSideKick }) /// } /// /// fn main() { /// match get_super_error() { /// Err(e) => { /// println!("Error: {}", e); /// println!("Caused by: {}", e.source().unwrap()); /// } /// _ => println!("No error"), /// } /// } /// ``` fn source(&self) -> Option<&(dyn Error + 'static)> { None } /// ``` /// if let Err(e) = "xc".parse::<u32>() { /// // Print `e` itself, no need for description(). /// eprintln!("Error: {}", e); /// } /// ``` #[deprecated(since = "1.42.0", note = "use `Display`")] fn description(&self) -> &str { "description() is deprecated; use Display" } #[deprecated(since = "1.33.0", note = "obsoleted by Error::source, which can support downcasting")] #[allow(missing_docs)] fn cause(&self) -> Option<&dyn Error> { self.source() } }