On this page
Struct std::io::Error
pub struct Error { /* private fields */ }
The error type for I/O operations of the Read
, Write
, Seek
, and associated traits.
Errors mostly originate from the underlying OS, but custom instances of Error
can be created with crafted error messages and a particular value of ErrorKind
.
Implementations
impl Error
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
E: Into<Box<dyn Error + Send + Sync>>,
Creates a new I/O error from a known kind of error as well as an arbitrary error payload.
This function is used to generically create I/O errors which do not originate from the OS itself. The error
argument is an arbitrary payload which will be contained in this Error
.
Note that this function allocates memory on the heap. If no extra payload is required, use the From
conversion from ErrorKind
.
Examples
use std::io::{Error, ErrorKind};
// errors can be created from strings
let custom_error = Error::new(ErrorKind::Other, "oh no!");
// errors can also be created from other errors
let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
// creating an error without payload (and without memory allocation)
let eof_error = Error::from(ErrorKind::UnexpectedEof);
pub fn other<E>(error: E) -> Error
where
E: Into<Box<dyn Error + Send + Sync>>,
Creates a new I/O error from an arbitrary error payload.
This function is used to generically create I/O errors which do not originate from the OS itself. It is a shortcut for Error::new
with ErrorKind::Other
.
Examples
use std::io::Error;
// errors can be created from strings
let custom_error = Error::other("oh no!");
// errors can also be created from other errors
let custom_error2 = Error::other(custom_error);
pub fn last_os_error() -> Error
Returns an error representing the last OS error which occurred.
This function reads the value of errno
for the target platform (e.g. GetLastError
on Windows) and will return a corresponding instance of Error
for the error code.
This should be called immediately after a call to a platform function, otherwise the state of the error value is indeterminate. In particular, other standard library functions may call platform functions that may (or may not) reset the error value even if they succeed.
Examples
use std::io::Error;
let os_error = Error::last_os_error();
println!("last OS error: {os_error:?}");
pub fn from_raw_os_error(code: RawOsError) -> Error
Creates a new instance of an Error
from a particular OS error code.
Examples
On Linux:
use std::io;
let error = io::Error::from_raw_os_error(22);
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
On Windows:
use std::io;
let error = io::Error::from_raw_os_error(10022);
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
pub fn raw_os_error(&self) -> Option<RawOsError>
Returns the OS error that this error represents (if any).
If this Error
was constructed via last_os_error
or from_raw_os_error
, then this function will return Some
, otherwise it will return None
.
Examples
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() {
// Will print "raw OS error: ...".
print_os_error(&Error::last_os_error());
// Will print "Not an OS error".
print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
}
pub fn get_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)>
Returns a reference to the inner error wrapped by this error (if any).
If this Error
was constructed via new
then this function will return Some
, otherwise it will return None
.
Examples
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() {
// Will print "No inner error".
print_error(&Error::last_os_error());
// Will print "Inner error: ...".
print_error(&Error::new(ErrorKind::Other, "oh no!"));
}
pub fn get_mut(&mut self) -> Option<&mut (dyn Error + Send + Sync + 'static)>
Returns a mutable reference to the inner error wrapped by this error (if any).
If this Error
was constructed via new
then this function will return Some
, otherwise it will return None
.
Examples
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() {
// Will print "No inner error".
print_error(&change_error(Error::last_os_error()));
// Will print "Inner error: ...".
print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
}
pub fn into_inner(self) -> Option<Box<dyn Error + Send + Sync>>
Consumes the Error
, returning its inner error (if any).
If this Error
was constructed via new
then this function will return Some
, otherwise it will return None
.
Examples
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() {
// Will print "No inner error".
print_error(Error::last_os_error());
// Will print "Inner error: ...".
print_error(Error::new(ErrorKind::Other, "oh no!"));
}
pub fn downcast<E>(self) -> Result<Box<E>, Self>
where
E: Error + Send + Sync + 'static,
io_error_downcast
#99262)
Attempt to downgrade the inner error to E
if any.
If this Error
was constructed via new
then this function will attempt to perform downgrade on it, otherwise it will return Err
.
If downgrade succeeds, it will return Ok
, otherwise it will also return Err
.
Examples
#![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)
}
}
pub fn kind(&self) -> ErrorKind
Returns the corresponding ErrorKind
for this error.
This may be a value set by Rust code constructing custom io::Error
s, or if this io::Error
was sourced from the operating system, it will be a value inferred from the system’s error encoding. See last_os_error
for more details.
Examples
use std::io::{Error, ErrorKind};
fn print_error(err: Error) {
println!("{:?}", err.kind());
}
fn main() {
// As no error has (visibly) occurred, this may print anything!
// It likely prints a placeholder for unidentified (non-)errors.
print_error(Error::last_os_error());
// Will print "AddrInUse".
print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
}
Trait Implementations
impl Debug for Error
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl Display for Error
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result
impl Error for Error
fn description(&self) -> &str
fn cause(&self) -> Option<&dyn Error>
fn source(&self) -> Option<&(dyn Error + 'static)>
fn provide<'a>(&'a self, request: &mut Request<'a>)
error_generic_member_access
#99301)
impl From<ErrorKind> for Error
Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly.
fn from(kind: ErrorKind) -> Error
impl<W> From<IntoInnerError<W>> for Error
fn from(iie: IntoInnerError<W>) -> Error
impl From<NulError> for Error
fn from(_: NulError) -> Error
Converts a alloc::ffi::NulError
into a 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
where
T: 'static + ?Sized,
impl<T> Borrow<T> for T
where
T: ?Sized,
impl<T> BorrowMut<T> for T
where
T: ?Sized,
impl<T> From<T> for T
fn from(t: T) -> T
Returns the argument unchanged.
impl<T, U> Into<U> for T
where
U: From<T>,
fn into(self) -> U
Calls U::from(self)
.
That is, this conversion is whatever the implementation of From<T> for U
chooses to do.
impl<T> ToString for T
where
T: Display + ?Sized,
impl<T, U> TryFrom<U> for T
where
U: Into<T>,
type Error = Infallible
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for T
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/io/struct.Error.html