Trait std::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>(&'a self) -> Option<&'a T>where T: 'static + ?Sized,

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

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

source

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

🔬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>(&self) -> boolwhere T: Error + 'static,

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

1.3.0 · source

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

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

1.3.0 · source

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

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

source§

impl dyn Error + Send + 'static

1.3.0 · source

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

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

1.3.0 · source

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

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

1.3.0 · source

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

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

source

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

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

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

source

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

🔬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>(&self) -> boolwhere T: Error + 'static,

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

1.3.0 · source

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

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

1.3.0 · source

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

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

source

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

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

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

source

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

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

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

source§

impl dyn Error + 'static

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
source§

impl dyn Error + Send + Sync + 'static

1.3.0 · source

pub fn downcast<T>( self: Box<dyn Error + Send + Sync + 'static, Global> ) -> Result<Box<T, Global>, Box<dyn Error + Send + Sync + 'static, Global>>where T: Error + 'static,

尝试将 box 向下转换为具体类型。

source§

impl dyn Error + Send + 'static

1.3.0 · source

pub fn downcast<T>( self: Box<dyn Error + Send + 'static, Global> ) -> Result<Box<T, Global>, Box<dyn Error + Send + 'static, Global>>where T: Error + 'static,

尝试将 box 向下转换为具体类型。

source§

impl dyn Error + 'static

1.3.0 · source

pub fn downcast<T>( self: Box<dyn Error + 'static, Global> ) -> Result<Box<T, Global>, Box<dyn Error + 'static, Global>>where T: Error + 'static,

尝试将 box 向下转换为具体类型。

Trait Implementations§

1.6.0 · source§

impl From<&str> for Box<dyn Error + 'static, Global>

source§

fn from(err: &str) -> Box<dyn Error + 'static, Global>

str 转换为 dyn Error 的 box。

Examples
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error>::from(a_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
source§

impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>

source§

fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a, Global>

str 转换为 Dyn Error + Send + Sync 的 box。

Examples
use std::error::Error;
use std::mem;

let a_str_error = "a str error";
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run
1.22.0 · source§

impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>

source§

fn from(err: Cow<'a, str>) -> Box<dyn Error + 'static, Global>

Cow 转换为 dyn Error 的 box。

Examples
use std::error::Error;
use std::mem;
use std::borrow::Cow;

let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
1.22.0 · source§

impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>

source§

fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a, Global>

Cow 转换为 Dyn Error + Send + Sync 的 box。

Examples
use std::error::Error;
use std::mem;
use std::borrow::Cow;

let a_cow_str_error = Cow::from("a str error");
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run
source§

impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where E: Error + 'a,

source§

fn from(err: E) -> Box<dyn Error + 'a, Global>

Error 的类型转换为 dyn Error 的 box。

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

#[derive(Debug)]
struct AnError;

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

impl Error for AnError {}

let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error>::from(an_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
source§

impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where E: Error + Send + Sync + 'a,

source§

fn from(err: E) -> Box<dyn Error + Send + Sync + 'a, Global>

Error + Send + Sync 的类型转换为 Dyn Error + Send + Sync 的 box。

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

#[derive(Debug)]
struct AnError;

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

impl Error for AnError {}

unsafe impl Send for AnError {}

unsafe impl Sync for AnError {}

let an_error = AnError;
assert!(0 == mem::size_of_val(&an_error));
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run
1.6.0 · source§

impl From<String> for Box<dyn Error + 'static, Global>

source§

fn from(str_err: String) -> Box<dyn Error + 'static, Global>

String 转换为 dyn Error 的 box。

Examples
use std::error::Error;
use std::mem;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error>::from(a_string_error);
assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
Run
source§

impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>

source§

fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>

String 转换为 Dyn Error + Send + Sync 的 box。

Examples
use std::error::Error;
use std::mem;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
    mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
Run

Implementors§

source§

impl !Error for &str

1.8.0 · source§

impl Error for Infallible

source§

impl Error for VarError

1.15.0 · source§

impl Error for RecvTimeoutError

source§

impl Error for TryRecvError

source§

impl Error for !

1.69.0 · source§

impl Error for FromBytesUntilNulError

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.57.0 · source§

impl Error for TryReserveError

source§

impl Error for JoinPathsError

1.17.0 · source§

impl Error for FromBytesWithNulError

1.58.0 · source§

impl Error for FromVecWithNulError

1.7.0 · source§

impl Error for IntoStringError

source§

impl Error for NulError

1.11.0 · source§

impl Error for std::fmt::Error

source§

impl Error for std::io::Error

1.56.0 · source§

impl Error for WriterPanicked

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

1.63.0 · source§

impl Error for InvalidHandleError

Available on Windows only.
1.63.0 · source§

impl Error for NullHandleError

Available on Windows only.
1.7.0 · source§

impl Error for StripPrefixError

source§

impl Error for ExitStatusError

source§

impl Error for ParseBoolError

source§

impl Error for Utf8Error

source§

impl Error for FromUtf8Error

source§

impl Error for FromUtf16Error

source§

impl Error for RecvError

1.26.0 · source§

impl Error for AccessError

1.8.0 · source§

impl Error for SystemTimeError

1.66.0 · source§

impl Error for TryFromFloatSecsError

source§

impl<'a, K, V> Error for std::collections::btree_map::OccupiedError<'a, K, V, Global>where K: Debug + Ord, V: Debug,

source§

impl<'a, K: Debug, V: Debug> Error for std::collections::hash_map::OccupiedError<'a, K, V>

1.51.0 · source§

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

source§

impl<T> Error for TryLockError<T>

source§

impl<T> Error for TrySendError<T>

1.8.0 · source§

impl<T> Error for Box<T, Global>where T: Error,

source§

impl<T> Error for ThinBox<T>where T: Error + ?Sized,

source§

impl<T> Error for SendError<T>

1.52.0 · source§

impl<T> Error for Arc<T>where T: Error + ?Sized,

source§

impl<T> Error for PoisonError<T>

source§

impl<W: Send + Debug> Error for IntoInnerError<W>

source§

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