Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Errors, Panics and Process

Rust io::Error and ErrorKind

Reference for std::io::Error and ErrorKind: matching on kinds like NotFound, raw OS error codes, creating custom I/O errors, io::Result and wrapping sources.

Almost every operation that touches files, sockets, pipes or the terminal returns std::io::Result<T>, which is an alias for Result<T, std::io::Error>. An io::Error carries a portable category (ErrorKind), and often the raw operating-system error number or a custom payload as well.

You normally react to the kind, not to the message text: NotFound means create the file, Interrupted means try again, UnexpectedEof means the input was cut short. The Display text, such as "No such file or directory (os error 2)", is for people.

Rust
use std::fs;
use std::io::ErrorKind;

match fs::read_to_string("settings.txt") {
    Ok(text) => println!("{} bytes", text.len()),
    Err(e) if e.kind() == ErrorKind::NotFound => println!("using defaults"),
    Err(e) => println!("failed: {e}"),
}

Try it

Rust Reacting to the error kind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Creating and wrapping io errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub type Result<T> = std::result::Result<T, io::Error>;

impl io::Error {
    pub fn new<E>(kind: ErrorKind, error: E) -> io::Error
        where E: Into<Box<dyn Error + Send + Sync>>;
    pub fn other<E>(error: E) -> io::Error
        where E: Into<Box<dyn Error + Send + Sync>>;
    pub fn kind(&self) -> ErrorKind;
    pub fn raw_os_error(&self) -> Option<i32>;
    pub fn last_os_error() -> io::Error;
    pub fn get_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)>;
    pub fn into_inner(self) -> Option<Box<dyn Error + Send + Sync>>;
}
impl From<ErrorKind> for io::Error { /* ... */ }
ErrorKind Typical cause
NotFound The file or directory does not exist.
PermissionDenied The OS refused access.
AlreadyExists Creating something that is already there (create_new, create_dir).
InvalidInput / InvalidData A bad argument / the bytes read are not valid for the format.
UnexpectedEof read_exact ran out of input.
WouldBlock A non-blocking operation has nothing ready yet.
Interrupted A system call was interrupted; retry.
BrokenPipe, ConnectionRefused, ConnectionReset, TimedOut Network and pipe failures.
Other Anything without a specific kind.

Usage notes

  • ErrorKind is #[non_exhaustive]; always keep a catch-all arm. New kinds appear in new Rust versions.
  • kind() for OS errors is a mapping done by the standard library. An OS error without a mapping appears as Uncategorized, which you cannot name in stable code; fall back to raw_os_error() if you need the number.
  • io::Error::new boxes the payload, so it allocates. From<ErrorKind> makes a "simple" error with no payload and no allocation.
  • io::Error is not Clone or PartialEq. Compare kind() values instead.
  • ? on a read, write or flush inside a function returning io::Result is the common style. Read::read_to_end and write_all already retry on Interrupted for you.
  • Mind the message: the error alone does not say which path failed. Add context yourself, for example map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}"))).
  • Wrap io::Error in your own error enum with a From impl so that ? converts it, and expose it through source().