4 use crate::convert::From;
10 /// A specialized [`Result`] type for I/O operations.
12 /// This type is broadly used across [`std::io`] for any operation which may
15 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
16 /// is otherwise a direct mapping to [`Result`].
18 /// While usual Rust style is to import types directly, aliases of [`Result`]
19 /// often are not, to make it easier to distinguish between them. [`Result`] is
20 /// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
21 /// will generally use `io::Result` instead of shadowing the [prelude]'s import
22 /// of [`std::result::Result`][`Result`].
24 /// [`std::io`]: crate::io
25 /// [`io::Error`]: Error
26 /// [`Result`]: crate::result::Result
27 /// [prelude]: crate::prelude
31 /// A convenience function that bubbles an `io::Result` to its caller:
36 /// fn get_string() -> io::Result<String> {
37 /// let mut buffer = String::new();
39 /// io::stdin().read_line(&mut buffer)?;
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub type Result<T> = result::Result<T, Error>;
47 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
48 /// associated traits.
50 /// Errors mostly originate from the underlying OS, but custom instances of
51 /// `Error` can be created with crafted error messages and a particular value of
54 /// [`Read`]: crate::io::Read
55 /// [`Write`]: crate::io::Write
56 /// [`Seek`]: crate::io::Seek
57 #[stable(feature = "rust1", since = "1.0.0")]
62 #[stable(feature = "rust1", since = "1.0.0")]
63 impl fmt::Debug for Error {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 fmt::Debug::fmt(&self.repr, f)
78 error: Box<dyn error::Error + Send + Sync>,
81 /// A list specifying general categories of I/O error.
83 /// This list is intended to grow over time and it is not recommended to
84 /// exhaustively match against it.
86 /// It is used with the [`io::Error`] type.
88 /// [`io::Error`]: Error
89 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
90 #[stable(feature = "rust1", since = "1.0.0")]
94 /// An entity was not found, often a file.
95 #[stable(feature = "rust1", since = "1.0.0")]
97 /// The operation lacked the necessary privileges to complete.
98 #[stable(feature = "rust1", since = "1.0.0")]
100 /// The connection was refused by the remote server.
101 #[stable(feature = "rust1", since = "1.0.0")]
103 /// The connection was reset by the remote server.
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// The connection was aborted (terminated) by the remote server.
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// The network operation failed because it was not connected yet.
110 #[stable(feature = "rust1", since = "1.0.0")]
112 /// A socket address could not be bound because the address is already in
114 #[stable(feature = "rust1", since = "1.0.0")]
116 /// A nonexistent interface was requested or the requested address was not
118 #[stable(feature = "rust1", since = "1.0.0")]
120 /// The operation failed because a pipe was closed.
121 #[stable(feature = "rust1", since = "1.0.0")]
123 /// An entity already exists, often a file.
124 #[stable(feature = "rust1", since = "1.0.0")]
126 /// The operation needs to block to complete, but the blocking operation was
127 /// requested to not occur.
128 #[stable(feature = "rust1", since = "1.0.0")]
130 /// A parameter was incorrect.
131 #[stable(feature = "rust1", since = "1.0.0")]
133 /// Data not valid for the operation were encountered.
135 /// Unlike [`InvalidInput`], this typically means that the operation
136 /// parameters were valid, however the error was caused by malformed
139 /// For example, a function that reads a file into a string will error with
140 /// `InvalidData` if the file's contents are not valid UTF-8.
142 /// [`InvalidInput`]: ErrorKind::InvalidInput
143 #[stable(feature = "io_invalid_data", since = "1.2.0")]
145 /// The I/O operation's timeout expired, causing it to be canceled.
146 #[stable(feature = "rust1", since = "1.0.0")]
148 /// An error returned when an operation could not be completed because a
149 /// call to [`write`] returned [`Ok(0)`].
151 /// This typically means that an operation could only succeed if it wrote a
152 /// particular number of bytes but only a smaller number of bytes could be
155 /// [`write`]: crate::io::Write::write
157 #[stable(feature = "rust1", since = "1.0.0")]
159 /// This operation was interrupted.
161 /// Interrupted operations can typically be retried.
162 #[stable(feature = "rust1", since = "1.0.0")]
164 /// Any I/O error not part of this list.
166 /// Errors that are `Other` now may move to a different or a new
167 /// [`ErrorKind`] variant in the future. It is not recommended to match
168 /// an error against `Other` and to expect any additional characteristics,
169 /// e.g., a specific [`Error::raw_os_error`] return value.
170 #[stable(feature = "rust1", since = "1.0.0")]
173 /// An error returned when an operation could not be completed because an
174 /// "end of file" was reached prematurely.
176 /// This typically means that an operation could only succeed if it read a
177 /// particular number of bytes but only a smaller number of bytes could be
179 #[stable(feature = "read_exact", since = "1.6.0")]
184 pub(crate) fn as_str(&self) -> &'static str {
186 ErrorKind::NotFound => "entity not found",
187 ErrorKind::PermissionDenied => "permission denied",
188 ErrorKind::ConnectionRefused => "connection refused",
189 ErrorKind::ConnectionReset => "connection reset",
190 ErrorKind::ConnectionAborted => "connection aborted",
191 ErrorKind::NotConnected => "not connected",
192 ErrorKind::AddrInUse => "address in use",
193 ErrorKind::AddrNotAvailable => "address not available",
194 ErrorKind::BrokenPipe => "broken pipe",
195 ErrorKind::AlreadyExists => "entity already exists",
196 ErrorKind::WouldBlock => "operation would block",
197 ErrorKind::InvalidInput => "invalid input parameter",
198 ErrorKind::InvalidData => "invalid data",
199 ErrorKind::TimedOut => "timed out",
200 ErrorKind::WriteZero => "write zero",
201 ErrorKind::Interrupted => "operation interrupted",
202 ErrorKind::Other => "other os error",
203 ErrorKind::UnexpectedEof => "unexpected end of file",
208 /// Intended for use for errors not exposed to the user, where allocating onto
209 /// the heap (for normal construction via Error::new) is too costly.
210 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
211 impl From<ErrorKind> for Error {
212 /// Converts an [`ErrorKind`] into an [`Error`].
214 /// This conversion allocates a new error with a simple representation of error kind.
219 /// use std::io::{Error, ErrorKind};
221 /// let not_found = ErrorKind::NotFound;
222 /// let error = Error::from(not_found);
223 /// assert_eq!("entity not found", format!("{}", error));
226 fn from(kind: ErrorKind) -> Error {
227 Error { repr: Repr::Simple(kind) }
232 /// Creates a new I/O error from a known kind of error as well as an
233 /// arbitrary error payload.
235 /// This function is used to generically create I/O errors which do not
236 /// originate from the OS itself. The `error` argument is an arbitrary
237 /// payload which will be contained in this [`Error`].
242 /// use std::io::{Error, ErrorKind};
244 /// // errors can be created from strings
245 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
247 /// // errors can also be created from other errors
248 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn new<E>(kind: ErrorKind, error: E) -> Error
253 E: Into<Box<dyn error::Error + Send + Sync>>,
255 Self::_new(kind, error.into())
258 fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
259 Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
262 /// Returns an error representing the last OS error which occurred.
264 /// This function reads the value of `errno` for the target platform (e.g.
265 /// `GetLastError` on Windows) and will return a corresponding instance of
266 /// [`Error`] for the error code.
271 /// use std::io::Error;
273 /// println!("last OS error: {:?}", Error::last_os_error());
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn last_os_error() -> Error {
277 Error::from_raw_os_error(sys::os::errno() as i32)
280 /// Creates a new instance of an [`Error`] from a particular OS error code.
287 /// # if cfg!(target_os = "linux") {
290 /// let error = io::Error::from_raw_os_error(22);
291 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
298 /// # if cfg!(windows) {
301 /// let error = io::Error::from_raw_os_error(10022);
302 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn from_raw_os_error(code: i32) -> Error {
307 Error { repr: Repr::Os(code) }
310 /// Returns the OS error that this error represents (if any).
312 /// If this [`Error`] was constructed via [`last_os_error`] or
313 /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
314 /// it will return [`None`].
316 /// [`last_os_error`]: Error::last_os_error
317 /// [`from_raw_os_error`]: Error::from_raw_os_error
322 /// use std::io::{Error, ErrorKind};
324 /// fn print_os_error(err: &Error) {
325 /// if let Some(raw_os_err) = err.raw_os_error() {
326 /// println!("raw OS error: {:?}", raw_os_err);
328 /// println!("Not an OS error");
333 /// // Will print "raw OS error: ...".
334 /// print_os_error(&Error::last_os_error());
335 /// // Will print "Not an OS error".
336 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn raw_os_error(&self) -> Option<i32> {
342 Repr::Os(i) => Some(i),
343 Repr::Custom(..) => None,
344 Repr::Simple(..) => None,
348 /// Returns a reference to the inner error wrapped by this error (if any).
350 /// If this [`Error`] was constructed via [`new`] then this function will
351 /// return [`Some`], otherwise it will return [`None`].
353 /// [`new`]: Error::new
358 /// use std::io::{Error, ErrorKind};
360 /// fn print_error(err: &Error) {
361 /// if let Some(inner_err) = err.get_ref() {
362 /// println!("Inner error: {:?}", inner_err);
364 /// println!("No inner error");
369 /// // Will print "No inner error".
370 /// print_error(&Error::last_os_error());
371 /// // Will print "Inner error: ...".
372 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
375 #[stable(feature = "io_error_inner", since = "1.3.0")]
376 pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
378 Repr::Os(..) => None,
379 Repr::Simple(..) => None,
380 Repr::Custom(ref c) => Some(&*c.error),
384 /// Returns a mutable reference to the inner error wrapped by this error
387 /// If this [`Error`] was constructed via [`new`] then this function will
388 /// return [`Some`], otherwise it will return [`None`].
390 /// [`new`]: Error::new
395 /// use std::io::{Error, ErrorKind};
396 /// use std::{error, fmt};
397 /// use std::fmt::Display;
405 /// fn new() -> MyError {
407 /// v: "oh no!".to_string()
411 /// fn change_message(&mut self, new_message: &str) {
412 /// self.v = new_message.to_string();
416 /// impl error::Error for MyError {}
418 /// impl Display for MyError {
419 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420 /// write!(f, "MyError: {}", &self.v)
424 /// fn change_error(mut err: Error) -> Error {
425 /// if let Some(inner_err) = err.get_mut() {
426 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
431 /// fn print_error(err: &Error) {
432 /// if let Some(inner_err) = err.get_ref() {
433 /// println!("Inner error: {}", inner_err);
435 /// println!("No inner error");
440 /// // Will print "No inner error".
441 /// print_error(&change_error(Error::last_os_error()));
442 /// // Will print "Inner error: ...".
443 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
446 #[stable(feature = "io_error_inner", since = "1.3.0")]
447 pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
449 Repr::Os(..) => None,
450 Repr::Simple(..) => None,
451 Repr::Custom(ref mut c) => Some(&mut *c.error),
455 /// Consumes the `Error`, returning its inner error (if any).
457 /// If this [`Error`] was constructed via [`new`] then this function will
458 /// return [`Some`], otherwise it will return [`None`].
460 /// [`new`]: Error::new
465 /// use std::io::{Error, ErrorKind};
467 /// fn print_error(err: Error) {
468 /// if let Some(inner_err) = err.into_inner() {
469 /// println!("Inner error: {}", inner_err);
471 /// println!("No inner error");
476 /// // Will print "No inner error".
477 /// print_error(Error::last_os_error());
478 /// // Will print "Inner error: ...".
479 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
482 #[stable(feature = "io_error_inner", since = "1.3.0")]
483 pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
485 Repr::Os(..) => None,
486 Repr::Simple(..) => None,
487 Repr::Custom(c) => Some(c.error),
491 /// Returns the corresponding [`ErrorKind`] for this error.
496 /// use std::io::{Error, ErrorKind};
498 /// fn print_error(err: Error) {
499 /// println!("{:?}", err.kind());
503 /// // Will print "Other".
504 /// print_error(Error::last_os_error());
505 /// // Will print "AddrInUse".
506 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn kind(&self) -> ErrorKind {
512 Repr::Os(code) => sys::decode_error_kind(code),
513 Repr::Custom(ref c) => c.kind,
514 Repr::Simple(kind) => kind,
519 impl fmt::Debug for Repr {
520 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
522 Repr::Os(code) => fmt
524 .field("code", &code)
525 .field("kind", &sys::decode_error_kind(code))
526 .field("message", &sys::os::error_string(code))
528 Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
529 Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl fmt::Display for Error {
536 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
539 let detail = sys::os::error_string(code);
540 write!(fmt, "{} (os error {})", detail, code)
542 Repr::Custom(ref c) => c.error.fmt(fmt),
543 Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl error::Error for Error {
550 #[allow(deprecated, deprecated_in_future)]
551 fn description(&self) -> &str {
553 Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
554 Repr::Custom(ref c) => c.error.description(),
559 fn cause(&self) -> Option<&dyn error::Error> {
561 Repr::Os(..) => None,
562 Repr::Simple(..) => None,
563 Repr::Custom(ref c) => c.error.cause(),
567 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
569 Repr::Os(..) => None,
570 Repr::Simple(..) => None,
571 Repr::Custom(ref c) => c.error.source(),
576 fn _assert_error_is_sync_send() {
577 fn _is_sync_send<T: Sync + Send>() {}
578 _is_sync_send::<Error>();