pub struct Error { /* private fields */ }
Expand description

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

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.

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
let eof_error = Error::from(ErrorKind::UnexpectedEof);
🔬 This is a nightly-only experimental API. (io_error_other)

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
#![feature(io_error_other)]

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);

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:?}");

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);

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!"));
}

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!"));
}

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())));
}

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!"));
}

Returns the corresponding ErrorKind for this error.

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

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

fn main() {
    // Will print "Uncategorized".
    print_error(Error::last_os_error());
    // Will print "AddrInUse".
    print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
}

Trait Implementations

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

👎 Deprecated since 1.42.0:

use the Display impl or to_string()

👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

The lower-level source of this error, if any. Read more

🔬 This is a nightly-only experimental API. (backtrace)

Returns a stack backtrace, if available, of where this error occurred. Read more

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Convert the Error to an io::Error, preserving the original Error as the “inner error”. Note that this also makes the display of the error include the context.

This is different from into_io_error which returns the original io::Error.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Convert a serde_json::Error into an io::Error.

JSON syntax and data errors are turned into InvalidData IO errors. EOF errors are turned into UnexpectedEof IO errors.

use std::io;

enum MyError {
    Io(io::Error),
    Json(serde_json::Error),
}

impl From<serde_json::Error> for MyError {
    fn from(err: serde_json::Error) -> MyError {
        use serde_json::error::Category;
        match err.classify() {
            Category::Io => {
                MyError::Io(err.into())
            }
            Category::Syntax | Category::Data | Category::Eof => {
                MyError::Json(err)
            }
        }
    }
}

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly.

Converts an ErrorKind into an Error.

This conversion creates a new error with a simple representation of error kind.

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

let not_found = ErrorKind::NotFound;
let error = Error::from(not_found);
assert_eq!("entity not found", format!("{error}"));

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts a [alloc::ffi::NulError] into a io::Error.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

Converts to this type from the input type.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Converts a reference to Self into a dynamic trait object of Fail.

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait. Read more

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait. Read more

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s. Read more

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s. Read more

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait. Read more

Use this to cast from one trait object type to another. Read more

Use this to upcast a trait to one of its supertraits. Read more

Use this to cast from one trait object type to another. This method is more customizable than the dyn_cast method. Here you can also specify the “source” trait from which the cast is defined. This can for example allow using casts from a supertrait of the current trait object. Read more

Use this to cast from one trait object type to another. With this method the type parameter is a config type that uniquely specifies which cast should be preformed. Read more

Returns the “name” of the error. Read more

Returns a reference to the underlying cause of this failure, if it is an error that wraps other errors. Read more

Returns a reference to the Backtrace carried by this failure, if it carries one. Read more

Provides context for this failure. Read more

Wraps this failure in a compatibility wrapper that implements std::error::Error. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more