pub trait Error:Debug +Display { // Provided methods fnsource(&self) ->Option<&(dynError + 'static)> { ... } fndescription(&self) -> &str { ... } fncause(&self) ->Option<&dynError> { ... } fnprovide<'a>(&'a self, request: &mutRequest<'a>) { ... }}Expand description
Error is a trait representing the basic expectations for error values,i.e., values of typeE inResult<T, E>.
Errors must describe themselves through theDisplay andDebugtraits. Error messages are typically concise lowercase sentences withouttrailing punctuation:
leterr ="NaN".parse::<u32>().unwrap_err();assert_eq!(err.to_string(),"invalid digit found in string");§Error source
Errors may provide cause information.Error::source() is generallyused when errors cross “abstraction boundaries”. If one module must reportan error that is caused by an error from a lower-level module, it can allowaccessing that error viaError::source(). This makes it possible for thehigh-level module to provide its own errors while also revealing some of theimplementation for debugging.
In error types that wrap an underlying error, the underlying errorshould be either returned by the outer error’sError::source(), or renderedby the outer error’sDisplay implementation, but not both.
§Example
Implementing theError trait only requires thatDebug andDisplay are implemented too.
usestd::error::Error;usestd::fmt;usestd::path::PathBuf;#[derive(Debug)]structReadConfigError { path: PathBuf}implfmt::DisplayforReadConfigError {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {letpath =self.path.display();write!(f,"unable to read configuration at {path}") }}implErrorforReadConfigError {}Provided Methods§
1.30.0 ·Sourcefnsource(&self) ->Option<&(dynError + 'static)>
fnsource(&self) ->Option<&(dynError + 'static)>
Returns the lower-level source of this error, if any.
§Examples
usestd::error::Error;usestd::fmt;#[derive(Debug)]structSuperError { source: SuperErrorSideKick,}implfmt::DisplayforSuperError {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {write!(f,"SuperError is here!") }}implErrorforSuperError {fnsource(&self) ->Option<&(dynError +'static)> {Some(&self.source) }}#[derive(Debug)]structSuperErrorSideKick;implfmt::DisplayforSuperErrorSideKick {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {write!(f,"SuperErrorSideKick is here!") }}implErrorforSuperErrorSideKick {}fnget_super_error() ->Result<(), SuperError> {Err(SuperError { source: SuperErrorSideKick })}fnmain() {matchget_super_error() {Err(e) => {println!("Error: {e}");println!("Caused by: {}", e.source().unwrap()); }_=>println!("No error"), }}1.0.0 ·Sourcefndescription(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()
fndescription(&self) -> &str
fncause(&self) ->Option<&dynError>
Sourcefnprovide<'a>(&'a self, request: &mutRequest<'a>)
🔬This is a nightly-only experimental API. (error_generic_member_access #99301)
fnprovide<'a>(&'a self, request: &mutRequest<'a>)
error_generic_member_access #99301)Provides type-based access to context intended for error reports.
Used in conjunction withRequest::provide_value andRequest::provide_ref to extractreferences to member variables fromdyn Error trait objects.
§Example
#![feature(error_generic_member_access)]usecore::fmt;usecore::error::{request_ref, Request};#[derive(Debug)]enumMyLittleTeaPot { Empty,}#[derive(Debug)]structMyBacktrace {// ...}implMyBacktrace {fnnew() -> MyBacktrace {// ...}}#[derive(Debug)]structError { backtrace: MyBacktrace,}implfmt::DisplayforError {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {write!(f,"Example Error") }}implstd::error::ErrorforError {fnprovide<'a>(&'aself, request:&mutRequest<'a>) { request .provide_ref::<MyBacktrace>(&self.backtrace); }}fnmain() {letbacktrace = MyBacktrace::new();leterror = Error { backtrace };letdyn_error =&erroras&dynstd::error::Error;letbacktrace_ref = request_ref::<MyBacktrace>(dyn_error).unwrap();assert!(core::ptr::eq(&error.backtrace, backtrace_ref));assert!(request_ref::<MyLittleTeaPot>(dyn_error).is_none());}Implementations§
Source§impl dynError + 'static
impl dynError + 'static
1.3.0 ·Sourcepub fnis<T:Error + 'static>(&self) ->bool
pub fnis<T:Error + 'static>(&self) ->bool
Returnstrue if the inner type is the same asT.
1.3.0 ·Sourcepub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
pub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
Returns some reference to the inner value if it is of typeT, orNone if it isn’t.
1.3.0 ·Sourcepub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
pub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
Returns some mutable reference to the inner value if it is of typeT, orNone if it isn’t.
Source§impl dynError +Send + 'static
impl dynError +Send + 'static
1.3.0 ·Sourcepub fnis<T:Error + 'static>(&self) ->bool
pub fnis<T:Error + 'static>(&self) ->bool
Forwards to the method defined on the typedyn Error.
1.3.0 ·Sourcepub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
pub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
Forwards to the method defined on the typedyn Error.
1.3.0 ·Sourcepub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
pub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
Forwards to the method defined on the typedyn Error.
Source§impl dynError +Send +Sync + 'static
impl dynError +Send +Sync + 'static
1.3.0 ·Sourcepub fnis<T:Error + 'static>(&self) ->bool
pub fnis<T:Error + 'static>(&self) ->bool
Forwards to the method defined on the typedyn Error.
1.3.0 ·Sourcepub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
pub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>
Forwards to the method defined on the typedyn Error.
1.3.0 ·Sourcepub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
pub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>
Forwards to the method defined on the typedyn Error.
Source§impl dynError
impl dynError
Sourcepub fnsources(&self) ->Source<'_>ⓘ
🔬This is a nightly-only experimental API. (error_iter #58520)
pub fnsources(&self) ->Source<'_>ⓘ
error_iter #58520)Returns an iterator starting with the current error and continuing withrecursively callingError::source.
If you want to omit the current error and only use its sources,useskip(1).
§Examples
#![feature(error_iter)]usestd::error::Error;usestd::fmt;#[derive(Debug)]structA;#[derive(Debug)]structB(Option<Box<dynError +'static>>);implfmt::DisplayforA {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {write!(f,"A") }}implfmt::DisplayforB {fnfmt(&self, f:&mutfmt::Formatter<'_>) -> fmt::Result {write!(f,"B") }}implErrorforA {}implErrorforB {fnsource(&self) ->Option<&(dynError +'static)> {self.0.as_ref().map(|e| e.as_ref()) }}letb = B(Some(Box::new(A)));// let err : Box<Error> = b.into(); // orleterr =&bas&dynError;letmutiter = err.sources();assert_eq!("B".to_string(), iter.next().unwrap().to_string());assert_eq!("A".to_string(), iter.next().unwrap().to_string());assert!(iter.next().is_none());assert!(iter.next().is_none());