Skip to content

Struct std::io::Error

rust
pub struct Error { /* private fields */ }

ReadWriteSeek 和关联的 traits 的 I/O 操作的错误类型。

错误主要来自底层操作系统,但可以使用精心制作的错误消息和特定的 ErrorKind 值来创建 Error 的自定义实例。

Implementations

impl Error

new

根据已知的错误以及任意的错误有效载荷创建新的 I/O 错误。

此函数通常用于创建 I/O 错误,这些错误并非源于操作系统本身。 error 参数是将包含在此 Error 中的任意有效载荷。

请注意,此函数在堆上分配内存。 如果不需要额外的有效载荷,请使用来自 ErrorKindFrom 转换。

rust
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
    E: Into<Box<dyn Error + Send + Sync>>,

参数

  • kind:一个ErrorKind枚举,表示错误的语义类型
  • error:对错误的描述,可以是&strStringCow<str>,也可以是一个Error

返回值:返回一个I/O 错误对象

rust
use std::io::{Error, ErrorKind};

// 可以从字符串创建错误
let custom_error = Error::new(ErrorKind::Other, "oh no!");

// 错误也可以从其他错误中创建
let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);

// 在没有有效,载荷 (并且没有内存分配) 的情况下创建错误
let eof_error = Error::from(ErrorKind::UnexpectedEof);

other

从任意错误有效载荷创建新的 I/O 错误。

此函数通常用于创建 I/O 错误,这些错误并非源于操作系统本身。 它是 Error::newErrorKind::Other 的快捷方式。

rust
pub fn other<E>(error: E) -> Error
where
    E: Into<Box<dyn Error + Send + Sync>>,

参数

  • error:对错误的描述,可以是&strStringCow<str>,也可以是一个Error

返回值:返回一个I/O 错误对象

rust
#![feature(io_error_other)]

use std::io::Error;

// 可以从字符串创建错误
let custom_error = Error::other("oh no!");

// 错误也可以从其他错误中创建
let custom_error2 = Error::other(custom_error);

last_os_error

返回代表最近发生的操作系统错误的错误。

该函数读取目标平台的 errno 值 (例如, Windows 上的 GetLastError) 并将为错误代码返回相应的 Error 实例。

这应该在调用到平台函数之后立即调用,否则错误值的状态是不确定的。 特别是,其他标准库函数可能会调用平台函数,即使它们成功也可能 (或可能不会) 重置错误值。

rust
pub fn last_os_error() -> Error

返回值:返回一个I/O 错误对象

rust
use std::io::Error;

let os_error = Error::last_os_error();
println!("last OS error: {os_error:?}");

from_row_os_error

根据特定的操作系统错误代码创建 Error 的新实例。

也可能 (或可能不会) 重置错误值。

rust
pub fn from_raw_os_error(code: RawOsError) -> Error

参数

返回值:返回一个I/O 错误对象

在 Linux 上:

rust
use std::io;

let error = io::Error::from_raw_os_error(22);
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);

在 Windows 上:

rust
use std::io;

let error = io::Error::from_raw_os_error(10022);
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);

row_os_error

返回此错误表示的操作系统错误 (如果有)。

如果此 Error 是通过 last_os_errorfrom_raw_os_error 构造的,则此函数将返回 Some,否则它将返回 None

rust
pub fn raw_os_error(&self) -> Option<RawOsError>

返回值:返回一个Option,其中包含RawOsError->Error::raw_os_error 返回的原始操作系统错误代码的类型。

rust
use std::io::{Error, ErrorKind};

fn print_os_error(err: &Error) {
    if let Some(raw_os_err) = err.raw_os_error() {
        println!("raw OS error: {raw_os_err:?}");
    } else {
        println!("Not an OS error");
    }
}

fn main() {
    // 将打印 "raw OS error: ..."。
    print_os_error(&Error::last_os_error());
    // 将打印 "Not an OS error"。
    print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
}

get_ref

返回对此错误包装的内部错误 (如果有) 的引用。

如果此 Error 是通过 new 构造的,则此函数将返回 Some,否则它将返回 None

rust
pub fn get_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)>

返回值:返回一个Option,其中包含内部错误的不可变引用

rust
use std::io::{Error, ErrorKind};

fn print_error(err: &Error) {
    if let Some(inner_err) = err.get_ref() {
        println!("Inner error: {inner_err:?}");
    } else {
        println!("No inner error");
    }
}

fn main() {
    // 将打印 "No inner error"。
    print_error(&Error::last_os_error());
    // 将打印 "Inner error: ..."。
    print_error(&Error::new(ErrorKind::Other, "oh no!"));
}

get_mut

返回对此错误包装的内部错误的可变引用 (如果有)。

如果此 Error 是通过 new 构造的,则此函数将返回 Some,否则它将返回 None

rust
pub fn get_mut(&mut self) -> Option<&mut (dyn Error + Send + Sync + 'static)>

返回值:返回一个Option,其中包含内部错误的可变引用

rust
use std::io::{Error, ErrorKind};
use std::{error, fmt};
use std::fmt::Display;

#[derive(Debug)]
struct MyError {
    v: String,
}

impl MyError {
    fn new() -> MyError {
        MyError {
            v: "oh no!".to_string()
        }
    }

    fn change_message(&mut self, new_message: &str) {
        self.v = new_message.to_string();
    }
}

impl error::Error for MyError {}

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

fn change_error(mut err: Error) -> Error {
    if let Some(inner_err) = err.get_mut() {
        inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
    }
    err
}

fn print_error(err: &Error) {
    if let Some(inner_err) = err.get_ref() {
        println!("Inner error: {inner_err}");
    } else {
        println!("No inner error");
    }
}

fn main() {
    // 将打印 "No inner error"。
    print_error(&change_error(Error::last_os_error()));
    // 将打印 "Inner error: ..."。
    print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
}

into_inner

消耗 Error,并返回其内部错误 (如果有)。

rust
pub fn into_inner(self) -> Option<Box<dyn Error + Send + Sync>>

返回值:如果此 Error 是通过 new 构造的,则此函数将返回 Some,否则它将返回 None

rust
use std::io::{Error, ErrorKind};

fn print_error(err: Error) {
    if let Some(inner_err) = err.into_inner() {
        println!("Inner error: {inner_err}");
    } else {
        println!("No inner error");
    }
}

fn main() {
    // 将打印 "No inner error"。
    print_error(Error::last_os_error());
    // 将打印 "Inner error: ..."。
    print_error(Error::new(ErrorKind::Other, "oh no!"));
}

downcast

尝试将内部错误降级为 E (如果有)。

rust
pub fn downcast<E>(self) -> Result<Box<E>, Self>
where
    E: Error + Send + Sync + 'static,

返回值

  • 如果这个 Error 是通过 new 构建的,那么这个函数将尝试对其执行降级,否则它将返回 Err
  • 降级成功返回 Ok,否则返回 Err
rust
#![feature(io_error_downcast)]

use std::fmt;
use std::io;
use std::error::Error;

#[derive(Debug)]
enum E {
    Io(io::Error),
    SomeOtherVariant,
}

impl fmt::Display for E {
   // ...
}
impl Error for E {}

impl From<io::Error> for E {
    fn from(err: io::Error) -> E {
        err.downcast::<E>()
            .map(|b| *b)
            .unwrap_or_else(E::Io)
    }
}

kind

返回与此错误对应的 ErrorKind

这可能是由 Rust 代码构造自定义 io::Error 设置的值,或者如果此 io::Error 来自操作系统,它将是从系统错误编码推断的值。

有关详细信息,请参见 last_os_error

rust
pub fn kind(&self) -> ErrorKind

返回值:返回这个错误的种类,结果为ErrorKind中的枚举值

rust
use std::io::{Error, ErrorKind};

fn print_error(err: Error) {
    println!("{:?}", err.kind());
}

fn main() {
    // 由于没有发生 (visibly) 错误,这可能会打印任何内容!
    // 它可能会为未识别的 (非) 错误打印一个占位符。
    print_error(Error::last_os_error());
    // 将打印 "AddrInUse"。
    print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
}

Trait Implementations

impl Debug for Error

fmt

使用给定的格式化程序格式化该值。

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

impl Display for Error

fmt

使用给定的格式化程序格式化该值。

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

impl Error for Error

source

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

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

provide

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

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

impl From<ErrorKind> for Error

旨在用于未暴露给用户的错误,因为分配到堆上 (通过 Error::new 进行常规构建) 的代价太高了。

from

将 ErrorKind 转换为 Error。这种转换会创建一个带有错误类型的简单表示的新错误。

rust
fn from(kind: ErrorKind) -> Error

impl<W> From<IntoInnerError<W>> for Error

from

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

rust
fn from(iie: IntoInnerError<W>) -> Error

impl From<NulError> for Error

from

将 alloc::ffi::NulError 转换为 Error。

rust
fn from(_: NulError) -> Error

Auto Trait Implementations

impl !RefUnwindSafe for Error

impl Send for Error

impl Sync for Error

impl Unpin for Error

impl !UnwindSafe for Error

Blanket Implementations

impl<T> Any for T

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

impl<T> Borrow<T> for T

rust
impl<T> Borrow<T> for T
where
  T: ?Sized,

impl<T> BorrowMut<T> for T

rust
impl<T> BorrowMut<T> for T
where
  T: ?Sized,

impl<T> From<T> for T

impl<T, U> Into<U> for T

rust
impl<T, U> Into<U> for T
where
  U: From<T>,

impl<E> Provider for E

rust
impl<E> Provider for E
where
  E: Error + ?Sized,

impl<T> ToString for T

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

impl<T, U> TryFrom<U> for T

rust
impl<T, U> TryFrom<U> for T
where
  U: Into<T>,

impl<T, U> TryInto<U> for T

rust
impl<T, U> TryInto<U> for T
where
  U: TryFrom<T>,

MIT Licensed