Trait core::error::Error

1.0.0 · source ·
pub trait Error: Debug + Display {
    // Provided methods
    fn source(&self) -> Option<&(dyn Error + 'static)> { ... }
    fn description(&self) -> &str { ... }
    fn cause(&self) -> Option<&dyn Error> { ... }
    fn provide<'a>(&'a self, demand: &mut Demand<'a>) { ... }
}
Expand description

Error 是一个 trait,代表对错误值的基本期望,即 Result<T, E>E 类型的值。

错误必须通过 DisplayDebug traits 来描述自己。 错误消息通常是简洁的小写句子,没有尾随标点符号:

let err = "NaN".parse::<u32>().unwrap_err();
assert_eq!(err.to_string(), "invalid digit found in string");
Run

错误可能会提供原因信息。Error::source() 通常在错误交叉 “抽象边界” 时使用。 如果一个模块必须报告由下级模块的错误引起的错误,则它可以允许通过 Error::source() 访问该错误。

这使得高级模块可以提供自己的错误,同时也揭示一些用于调试的实现。

Provided Methods§

1.30.0 · source

fn source(&self) -> Option<&(dyn Error + 'static)>

此错误的下级来源 (如果有)。

Examples
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct SuperError {
    source: 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.source)
    }
}

#[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 { source: SuperErrorSideKick })
}

fn main() {
    match get_super_error() {
        Err(e) => {
            println!("Error: {e}");
            println!("Caused by: {}", e.source().unwrap());
        }
        _ => println!("No error"),
    }
}
Run
source

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
if let Err(e) = "xc".parse::<u32>() {
    // 打印 `e` 本身,不需要 description()。
    eprintln!("Error: {e}");
}
Run
source

fn cause(&self) -> Option<&dyn Error>

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

fn provide<'a>(&'a self, demand: &mut Demand<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

提供对用于错误报告的上下文的基于类型的访问。

Demand::provide_valueDemand::provide_ref 结合使用以从 dyn Error trait 对象中提取对成员参数的引用。

Example
#![feature(provide_any)]
#![feature(error_generic_member_access)]
use core::fmt;
use core::any::Demand;

#[derive(Debug)]
struct MyBacktrace {
    // ...
}

impl MyBacktrace {
    fn new() -> MyBacktrace {
        // ...
    }
}

#[derive(Debug)]
struct SourceError {
    // ...
}

impl fmt::Display for SourceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Example Source Error")
    }
}

impl std::error::Error for SourceError {}

#[derive(Debug)]
struct Error {
    source: SourceError,
    backtrace: MyBacktrace,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Example Error")
    }
}

impl std::error::Error for Error {
    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
        demand
            .provide_ref::<MyBacktrace>(&self.backtrace)
            .provide_ref::<dyn std::error::Error + 'static>(&self.source);
    }
}

fn main() {
    let backtrace = MyBacktrace::new();
    let source = SourceError {};
    let error = Error { source, backtrace };
    let dyn_error = &error as &dyn std::error::Error;
    let backtrace_ref = dyn_error.request_ref::<MyBacktrace>().unwrap();

    assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
}
Run

Implementations§

source§

impl<'a> dyn Error + 'a

source

pub fn request_ref<T: ?Sized + 'static>(&'a self) -> Option<&'a T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的引用作为有关此错误的上下文。

source

pub fn request_value<T: 'static>(&'a self) -> Option<T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的值作为有关此错误的上下文。

source§

impl dyn Error + 'static

1.3.0 · source

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

如果内部类型与 T 相同,则返回 true

1.3.0 · source

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

如果内部值的类型为 T 类型,则返回一些对内部值的引用,如果不是,则返回 None

1.3.0 · source

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

如果内部值的类型为 T 类型,则返回一些对内部值的引用,如果不是,则返回 None

source§

impl dyn Error + Send + 'static

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

source

pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的引用作为有关此错误的上下文。

source

pub fn request_value<T: 'static>(&self) -> Option<T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的值作为有关此错误的上下文。

source§

impl dyn Error + Send + Sync + 'static

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

1.3.0 · source

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

转发到在 dyn Error 类型上定义的方法。

source

pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的引用作为有关此错误的上下文。

source

pub fn request_value<T: 'static>(&self) -> Option<T>

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

请求 T 类型的值作为有关此错误的上下文。

source§

impl dyn Error

source

pub fn sources(&self) -> Source<'_>

🔬This is a nightly-only experimental API. (error_iter #58520)

返回一个迭代器,该迭代器从当前错误开始,然后以递归方式调用 Error::source

如果要忽略当前错误并仅使用其来源,请使用 skip(1)

Examples
#![feature(error_iter)]
use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct A;

#[derive(Debug)]
struct B(Option<Box<dyn Error + 'static>>);

impl fmt::Display for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "A")
    }
}

impl fmt::Display for B {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "B")
    }
}

impl Error for A {}

impl Error for B {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.as_ref().map(|e| e.as_ref())
    }
}

let b = B(Some(Box::new(A)));

// 令 err: Box<Error> = b.into(); // 或者
let err = &b as &(dyn Error);

let mut iter = 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());
Run

Implementors§

source§

impl !Error for &str

1.8.0 · source§

impl Error for Infallible

source§

impl Error for !

source§

impl Error for AllocError

1.28.0 · source§

impl Error for LayoutError

1.34.0 · source§

impl Error for TryFromSliceError

1.13.0 · source§

impl Error for BorrowError

1.13.0 · source§

impl Error for BorrowMutError

1.34.0 · source§

impl Error for CharTryFromError

1.9.0 · source§

impl Error for DecodeUtf16Error

1.20.0 · source§

impl Error for ParseCharError

1.59.0 · source§

impl Error for TryFromCharError

1.69.0 · source§

impl Error for FromBytesUntilNulError

1.17.0 · source§

impl Error for FromBytesWithNulError

1.11.0 · source§

impl Error for Error

1.4.0 · source§

impl Error for AddrParseError

source§

impl Error for ParseFloatError

source§

impl Error for ParseIntError

1.34.0 · source§

impl Error for TryFromIntError

source§

impl Error for ParseBoolError

source§

impl Error for Utf8Error

1.66.0 · source§

impl Error for TryFromFloatSecsError

1.51.0 · source§

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

source§

impl<const N: usize> Error for GetManyMutError<N>