Struct std::error::Report

source ·
pub struct Report<E = Box<dyn Error>> { /* private fields */ }
🔬This is a nightly-only experimental API. (error_reporter #90172)
Expand description

打印错误及其来源的错误报告器。

报告还公开了用于格式化错误源的配置选项,可以完全在单行上,也可以在多行格式中,每个源在新行上。

Report 只要求包装的错误实现 Error。它不需要包装的错误是 SendSync'static

Examples

#![feature(error_reporter)]
use std::error::{Error, Report};
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: {}", Report::new(e)),
        _ => println!("No error"),
    }
}
Run

此示例产生以下输出:

Error: SuperError is here!: SuperErrorSideKick is here!

输出一致性

报告通过 DisplayDebug 打印相同的输出,因此,它可以很好地与 Result::unwrap/Result::expect 配合使用,通过 Debug 打印其 Err 变体:

#![feature(error_reporter)]
use std::error::Report;

get_super_error().map_err(Report::new).unwrap();
Run

此示例产生以下输出:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

main 返回

Report 还为所有实现 Error 的类型实现 From; 这与 Debug 输出相结合意味着 Report 是从 main 返回的格式化错误的理想起点。

#![feature(error_reporter)]
use std::error::Report;

fn main() -> Result<(), Report<SuperError>> {
    get_super_error()?;
    Ok(())
}
Run

此示例产生以下输出:

Error: SuperError is here!: SuperErrorSideKick is here!

Note: 通过 ?From 构造的报表将被配置为使用单行输出格式。 如果您想确保您的 报告 打印得非常漂亮并包含回溯,您将需要手动转换并启用这些标志。

#![feature(error_reporter)]
use std::error::Report;

fn main() -> Result<(), Report<SuperError>> {
    get_super_error()
        .map_err(Report::from)
        .map_err(|r| r.pretty(true).show_backtrace(true))?;
    Ok(())
}
Run

此示例产生以下输出:

Error: SuperError is here!

Caused by:
      SuperErrorSideKick is here!

Implementations§

source§

impl<E> Report<E>where Report<E>: From<E>,

source

pub fn new(error: E) -> Report<E>

🔬This is a nightly-only experimental API. (error_reporter #90172)

从输入错误创建一个新的 Report

source§

impl<E> Report<E>

source

pub fn pretty(self, pretty: bool) -> Self

🔬This is a nightly-only experimental API. (error_reporter #90172)

启用跨多行的漂亮打印报告。

Examples
#![feature(error_reporter)]
use std::error::Report;

let error = SuperError { source: SuperErrorSideKick };
let report = Report::new(error).pretty(true);
eprintln!("Error: {report:?}");
Run

此示例产生以下输出:

Error: SuperError is here!

Caused by:
      SuperErrorSideKick is here!

当有多个源错误时,将按照从最外层错误开始的迭代顺序对原因进行编号。

#![feature(error_reporter)]
use std::error::Report;

let source = SuperErrorSideKickSideKick;
let source = SuperErrorSideKick { source };
let error = SuperError { source };
let report = Report::new(error).pretty(true);
eprintln!("Error: {report:?}");
Run

此示例产生以下输出:

Error: SuperError is here!

Caused by:
   0: SuperErrorSideKick is here!
   1: SuperErrorSideKickSideKick is here!
source

pub fn show_backtrace(self, show_backtrace: bool) -> Self

🔬This is a nightly-only experimental API. (error_reporter #90172)

使用漂亮的输出格式时,会显示回溯 (如果可用)。

Examples

Note: 报告将从最外层错误开始搜索它可以找到的第一个 Backtrace。 在此示例中,它将显示源中第二个错误 SuperErrorSideKick 的回溯。

#![feature(error_reporter)]
#![feature(provide_any)]
#![feature(error_generic_member_access)]
use std::any::Demand;
use std::error::Report;
use std::backtrace::Backtrace;

#[derive(Debug)]
struct SuperErrorSideKick {
    backtrace: Backtrace,
}

impl SuperErrorSideKick {
    fn new() -> SuperErrorSideKick {
        SuperErrorSideKick { backtrace: Backtrace::force_capture() }
    }
}

impl Error for SuperErrorSideKick {
    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
        demand.provide_ref::<Backtrace>(&self.backtrace);
    }
}

// 示例的其余部分保持不变 ...

let source = SuperErrorSideKick::new();
let error = SuperError { source };
let report = Report::new(error).pretty(true).show_backtrace(true);
eprintln!("Error: {report:?}");
Run

此示例产生类似于以下输出的内容:

Error: SuperError is here!

Caused by:
      SuperErrorSideKick is here!

Stack backtrace:
   0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
   1: rust_out::main::_doctest_main_src_error_rs_1158_0
   2: rust_out::main
   3: core::ops::function::FnOnce::call_once
   4: std::sys_common::backtrace::__rust_begin_short_backtrace
   5: std::rt::lang_start::{{closure}}
   6: std::panicking::try
   7: std::rt::lang_start_internal
   8: std::rt::lang_start
   9: main
  10: __libc_start_main
  11: _start

Trait Implementations§

source§

impl<E> Debug for Report<E>where Report<E>: Display,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

使用给定的格式化程序格式化该值。 Read more
source§

impl<E> Display for Report<E>where E: Error,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

使用给定的格式化程序格式化该值。 Read more
source§

impl<E> From<E> for Report<E>where E: Error,

source§

fn from(error: E) -> Self

从输入类型转换为此类型。

Auto Trait Implementations§

§

impl<E> RefUnwindSafe for Report<E>where E: RefUnwindSafe,

§

impl<E> Send for Report<E>where E: Send,

§

impl<E> Sync for Report<E>where E: Sync,

§

impl<E> Unpin for Report<E>where E: Unpin,

§

impl<E> UnwindSafe for Report<E>where E: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

获取 selfTypeIdRead more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

从拥有的值中一成不变地借用。 Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

从拥有的值中借用。 Read more
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

从输入类型转换为此类型。
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

返回未更改的参数。

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

调用 U::from(self)

也就是说,这种转换是 From<T> for U 实现选择执行的任何操作。

source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

将给定值转换为 StringRead more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

发生转换错误时返回的类型。
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

发生转换错误时返回的类型。
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。