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
类型的值。
错误必须通过 Display
和 Debug
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 · sourcefn source(&self) -> Option<&(dyn Error + 'static)>
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"),
}
}
Runsourcefn description(&self) -> &str
fn description(&self) -> &str
if let Err(e) = "xc".parse::<u32>() {
// 打印 `e` 本身,不需要 description()。
eprintln!("Error: {e}");
}
Runsourcefn cause(&self) -> Option<&dyn Error>
fn cause(&self) -> Option<&dyn Error>
sourcefn provide<'a>(&'a self, demand: &mut Demand<'a>)
fn provide<'a>(&'a self, demand: &mut Demand<'a>)
error_generic_member_access
#99301)提供对用于错误报告的上下文的基于类型的访问。
与 Demand::provide_value
和 Demand::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));
}
RunImplementations§
source§impl<'a> dyn Error + 'a
impl<'a> dyn Error + 'a
sourcepub 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)
pub fn request_ref<T>(&'a self) -> Option<&'a T>where T: 'static + ?Sized,
error_generic_member_access
#99301)请求 T
类型的引用作为有关此错误的上下文。
sourcepub fn request_value<T>(&'a self) -> Option<T>where
T: 'static,
🔬This is a nightly-only experimental API. (error_generic_member_access
#99301)
pub fn request_value<T>(&'a self) -> Option<T>where T: 'static,
error_generic_member_access
#99301)请求 T
类型的值作为有关此错误的上下文。
source§impl dyn Error + 'static
impl dyn Error + 'static
1.3.0 · sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: Error + 'static,
pub fn downcast_ref<T>(&self) -> Option<&T>where T: Error + 'static,
如果内部值的类型为 T
类型,则返回一些对内部值的引用,如果不是,则返回 None
。
1.3.0 · sourcepub fn downcast_mut<T>(&mut self) -> Option<&mut T>where
T: Error + 'static,
pub fn downcast_mut<T>(&mut self) -> Option<&mut T>where T: Error + 'static,
如果内部值的类型为 T
类型,则返回一些对内部值的引用,如果不是,则返回 None
。
source§impl dyn Error + Send + 'static
impl dyn Error + Send + 'static
1.3.0 · sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: Error + 'static,
pub fn downcast_ref<T>(&self) -> Option<&T>where T: Error + 'static,
转发到在 dyn Error
类型上定义的方法。
1.3.0 · sourcepub fn downcast_mut<T>(&mut self) -> Option<&mut T>where
T: Error + 'static,
pub fn downcast_mut<T>(&mut self) -> Option<&mut T>where T: Error + 'static,
转发到在 dyn Error
类型上定义的方法。
sourcepub fn request_ref<T>(&self) -> Option<&T>where
T: 'static + ?Sized,
🔬This is a nightly-only experimental API. (error_generic_member_access
#99301)
pub fn request_ref<T>(&self) -> Option<&T>where T: 'static + ?Sized,
error_generic_member_access
#99301)请求 T
类型的引用作为有关此错误的上下文。
sourcepub fn request_value<T>(&self) -> Option<T>where
T: 'static,
🔬This is a nightly-only experimental API. (error_generic_member_access
#99301)
pub fn request_value<T>(&self) -> Option<T>where T: 'static,
error_generic_member_access
#99301)请求 T
类型的值作为有关此错误的上下文。
source§impl dyn Error + Send + Sync + 'static
impl dyn Error + Send + Sync + 'static
1.3.0 · sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: Error + 'static,
pub fn downcast_ref<T>(&self) -> Option<&T>where T: Error + 'static,
转发到在 dyn Error
类型上定义的方法。
1.3.0 · sourcepub fn downcast_mut<T>(&mut self) -> Option<&mut T>where
T: Error + 'static,
pub fn downcast_mut<T>(&mut self) -> Option<&mut T>where T: Error + 'static,
转发到在 dyn Error
类型上定义的方法。
sourcepub fn request_ref<T>(&self) -> Option<&T>where
T: 'static + ?Sized,
🔬This is a nightly-only experimental API. (error_generic_member_access
#99301)
pub fn request_ref<T>(&self) -> Option<&T>where T: 'static + ?Sized,
error_generic_member_access
#99301)请求 T
类型的引用作为有关此错误的上下文。
sourcepub fn request_value<T>(&self) -> Option<T>where
T: 'static,
🔬This is a nightly-only experimental API. (error_generic_member_access
#99301)
pub fn request_value<T>(&self) -> Option<T>where T: 'static,
error_generic_member_access
#99301)请求 T
类型的值作为有关此错误的上下文。
source§impl dyn Error + 'static
impl dyn Error + 'static
sourcepub fn sources(&self) -> Source<'_> ⓘ
🔬This is a nightly-only experimental API. (error_iter
#58520)
pub fn sources(&self) -> Source<'_> ⓘ
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());
RunTrait Implementations§
1.6.0 · source§impl From<&str> for Box<dyn Error + 'static, Global>
impl From<&str> for Box<dyn Error + 'static, Global>
source§impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a, Global>
1.22.0 · source§impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
impl<'a> From<Cow<'a, str>> for Box<dyn Error + 'static, Global>
1.22.0 · source§impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a, Global>
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>
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))
Runsource§impl<'a, E> From<E> for Box<dyn Error + 'a, Global>where
E: Error + 'a,
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>
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))
Runsource§impl<'a, E> From<E> for Box<dyn Error + Send + Sync + 'a, Global>where
E: Error + Send + Sync + 'a,
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>
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))
Run1.6.0 · source§impl From<String> for Box<dyn Error + 'static, Global>
impl From<String> for Box<dyn Error + 'static, Global>
source§impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
impl From<String> for Box<dyn Error + Send + Sync + 'static, Global>
source§fn from(err: String) -> Box<dyn Error + Send + Sync + 'static, Global>
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