Movatterモバイル変換


[0]ホーム

URL:


Error

core::error

TraitError 

1.81.0 ·Source
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 ·Source

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 ·Source

fndescription(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
if letErr(e) ="xc".parse::<u32>() {// Print `e` itself, no need for description().eprintln!("Error: {e}");}
1.0.0 ·Source

fncause(&self) ->Option<&dynError>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source

fnprovide<'a>(&'a self, request: &mutRequest<'a>)

🔬This is a nightly-only experimental API. (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

1.3.0 ·Source

pub fnis<T:Error + 'static>(&self) ->bool

Returnstrue if the inner type is the same asT.

1.3.0 ·Source

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 ·Source

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

1.3.0 ·Source

pub fnis<T:Error + 'static>(&self) ->bool

Forwards to the method defined on the typedyn Error.

1.3.0 ·Source

pub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>

Forwards to the method defined on the typedyn Error.

1.3.0 ·Source

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

1.3.0 ·Source

pub fnis<T:Error + 'static>(&self) ->bool

Forwards to the method defined on the typedyn Error.

1.3.0 ·Source

pub fndowncast_ref<T:Error + 'static>(&self) ->Option<&T>

Forwards to the method defined on the typedyn Error.

1.3.0 ·Source

pub fndowncast_mut<T:Error + 'static>(&mut self) ->Option<&mut T>

Forwards to the method defined on the typedyn Error.

Source§

impl dynError

Source

pub fnsources(&self) ->Source<'_>

🔬This is a nightly-only experimental API. (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());

Implementors§

1.65.0 ·Source§

impl !Error for &str

1.8.0 ·Source§

implError forInfallible

1.17.0 ·Source§

implError forFromBytesWithNulError

1.86.0 ·Source§

implError forGetDisjointMutError

Source§

implError for!

Source§

implError forAllocError

1.28.0 ·Source§

implError forLayoutError

1.34.0 ·Source§

implError forTryFromSliceError

1.13.0 ·Source§

implError forBorrowError

1.13.0 ·Source§

implError forBorrowMutError

1.34.0 ·Source§

implError forCharTryFromError

1.9.0 ·Source§

implError forDecodeUtf16Error

1.20.0 ·Source§

implError forParseCharError

1.59.0 ·Source§

implError forTryFromCharError

1.69.0 ·Source§

implError forFromBytesUntilNulError

1.11.0 ·Source§

implError forError

1.4.0 ·Source§

implError forAddrParseError

1.0.0 ·Source§

implError forParseFloatError

1.0.0 ·Source§

implError forParseIntError

1.34.0 ·Source§

implError forTryFromIntError

1.0.0 ·Source§

implError forParseBoolError

1.0.0 ·Source§

implError forUtf8Error

1.66.0 ·Source§

implError forTryFromFloatSecsError

1.51.0 ·Source§

impl<'a, T:Error + ?Sized>Error for&'a T


[8]ページ先頭

©2009-2025 Movatter.jp