1 use crate::convert::From;
7 /// A specialized [`Result`] type for I/O operations.
9 /// This type is broadly used across [`std::io`] for any operation which may
12 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
13 /// is otherwise a direct mapping to [`Result`].
15 /// While usual Rust style is to import types directly, aliases of [`Result`]
16 /// often are not, to make it easier to distinguish between them. [`Result`] is
17 /// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
18 /// will generally use `io::Result` instead of shadowing the [prelude]'s import
19 /// of [`std::result::Result`][`Result`].
21 /// [`std::io`]: crate::io
22 /// [`io::Error`]: Error
23 /// [`Result`]: crate::result::Result
24 /// [prelude]: crate::prelude
28 /// A convenience function that bubbles an `io::Result` to its caller:
33 /// fn get_string() -> io::Result<String> {
34 /// let mut buffer = String::new();
36 /// io::stdin().read_line(&mut buffer)?;
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub type Result<T> = result::Result<T, Error>;
44 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
45 /// associated traits.
47 /// Errors mostly originate from the underlying OS, but custom instances of
48 /// `Error` can be created with crafted error messages and a particular value of
51 /// [`Read`]: crate::io::Read
52 /// [`Write`]: crate::io::Write
53 /// [`Seek`]: crate::io::Seek
54 #[stable(feature = "rust1", since = "1.0.0")]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 impl fmt::Debug for Error {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 fmt::Debug::fmt(&self.repr, f)
75 error: Box<dyn error::Error + Send + Sync>,
78 /// A list specifying general categories of I/O error.
80 /// This list is intended to grow over time and it is not recommended to
81 /// exhaustively match against it.
83 /// It is used with the [`io::Error`] type.
85 /// [`io::Error`]: Error
86 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
87 #[stable(feature = "rust1", since = "1.0.0")]
91 /// An entity was not found, often a file.
92 #[stable(feature = "rust1", since = "1.0.0")]
94 /// The operation lacked the necessary privileges to complete.
95 #[stable(feature = "rust1", since = "1.0.0")]
97 /// The connection was refused by the remote server.
98 #[stable(feature = "rust1", since = "1.0.0")]
100 /// The connection was reset by the remote server.
101 #[stable(feature = "rust1", since = "1.0.0")]
103 /// The connection was aborted (terminated) by the remote server.
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// The network operation failed because it was not connected yet.
107 #[stable(feature = "rust1", since = "1.0.0")]
109 /// A socket address could not be bound because the address is already in
111 #[stable(feature = "rust1", since = "1.0.0")]
113 /// A nonexistent interface was requested or the requested address was not
115 #[stable(feature = "rust1", since = "1.0.0")]
117 /// The operation failed because a pipe was closed.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 /// An entity already exists, often a file.
121 #[stable(feature = "rust1", since = "1.0.0")]
123 /// The operation needs to block to complete, but the blocking operation was
124 /// requested to not occur.
125 #[stable(feature = "rust1", since = "1.0.0")]
127 /// A parameter was incorrect.
128 #[stable(feature = "rust1", since = "1.0.0")]
130 /// Data not valid for the operation were encountered.
132 /// Unlike [`InvalidInput`], this typically means that the operation
133 /// parameters were valid, however the error was caused by malformed
136 /// For example, a function that reads a file into a string will error with
137 /// `InvalidData` if the file's contents are not valid UTF-8.
139 /// [`InvalidInput`]: ErrorKind::InvalidInput
140 #[stable(feature = "io_invalid_data", since = "1.2.0")]
142 /// The I/O operation's timeout expired, causing it to be canceled.
143 #[stable(feature = "rust1", since = "1.0.0")]
145 /// An error returned when an operation could not be completed because a
146 /// call to [`write`] returned [`Ok(0)`].
148 /// This typically means that an operation could only succeed if it wrote a
149 /// particular number of bytes but only a smaller number of bytes could be
152 /// [`write`]: crate::io::Write::write
154 #[stable(feature = "rust1", since = "1.0.0")]
156 /// This operation was interrupted.
158 /// Interrupted operations can typically be retried.
159 #[stable(feature = "rust1", since = "1.0.0")]
161 /// Any I/O error not part of this list.
163 /// Errors that are `Other` now may move to a different or a new
164 /// [`ErrorKind`] variant in the future. It is not recommended to match
165 /// an error against `Other` and to expect any additional characteristics,
166 /// e.g., a specific [`Error::raw_os_error`] return value.
167 #[stable(feature = "rust1", since = "1.0.0")]
170 /// An error returned when an operation could not be completed because an
171 /// "end of file" was reached prematurely.
173 /// This typically means that an operation could only succeed if it read a
174 /// particular number of bytes but only a smaller number of bytes could be
176 #[stable(feature = "read_exact", since = "1.6.0")]
181 pub(crate) fn as_str(&self) -> &'static str {
183 ErrorKind::NotFound => "entity not found",
184 ErrorKind::PermissionDenied => "permission denied",
185 ErrorKind::ConnectionRefused => "connection refused",
186 ErrorKind::ConnectionReset => "connection reset",
187 ErrorKind::ConnectionAborted => "connection aborted",
188 ErrorKind::NotConnected => "not connected",
189 ErrorKind::AddrInUse => "address in use",
190 ErrorKind::AddrNotAvailable => "address not available",
191 ErrorKind::BrokenPipe => "broken pipe",
192 ErrorKind::AlreadyExists => "entity already exists",
193 ErrorKind::WouldBlock => "operation would block",
194 ErrorKind::InvalidInput => "invalid input parameter",
195 ErrorKind::InvalidData => "invalid data",
196 ErrorKind::TimedOut => "timed out",
197 ErrorKind::WriteZero => "write zero",
198 ErrorKind::Interrupted => "operation interrupted",
199 ErrorKind::Other => "other os error",
200 ErrorKind::UnexpectedEof => "unexpected end of file",
205 /// Intended for use for errors not exposed to the user, where allocating onto
206 /// the heap (for normal construction via Error::new) is too costly.
207 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
208 impl From<ErrorKind> for Error {
209 /// Converts an [`ErrorKind`] into an [`Error`].
211 /// This conversion allocates a new error with a simple representation of error kind.
216 /// use std::io::{Error, ErrorKind};
218 /// let not_found = ErrorKind::NotFound;
219 /// let error = Error::from(not_found);
220 /// assert_eq!("entity not found", format!("{}", error));
223 fn from(kind: ErrorKind) -> Error {
224 Error { repr: Repr::Simple(kind) }
229 /// Creates a new I/O error from a known kind of error as well as an
230 /// arbitrary error payload.
232 /// This function is used to generically create I/O errors which do not
233 /// originate from the OS itself. The `error` argument is an arbitrary
234 /// payload which will be contained in this [`Error`].
239 /// use std::io::{Error, ErrorKind};
241 /// // errors can be created from strings
242 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
244 /// // errors can also be created from other errors
245 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn new<E>(kind: ErrorKind, error: E) -> Error
250 E: Into<Box<dyn error::Error + Send + Sync>>,
252 Self::_new(kind, error.into())
255 fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
256 Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
259 /// Returns an error representing the last OS error which occurred.
261 /// This function reads the value of `errno` for the target platform (e.g.
262 /// `GetLastError` on Windows) and will return a corresponding instance of
263 /// [`Error`] for the error code.
268 /// use std::io::Error;
270 /// println!("last OS error: {:?}", Error::last_os_error());
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub fn last_os_error() -> Error {
274 Error::from_raw_os_error(sys::os::errno() as i32)
277 /// Creates a new instance of an [`Error`] from a particular OS error code.
284 /// # if cfg!(target_os = "linux") {
287 /// let error = io::Error::from_raw_os_error(22);
288 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
295 /// # if cfg!(windows) {
298 /// let error = io::Error::from_raw_os_error(10022);
299 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn from_raw_os_error(code: i32) -> Error {
304 Error { repr: Repr::Os(code) }
307 /// Returns the OS error that this error represents (if any).
309 /// If this [`Error`] was constructed via [`last_os_error`] or
310 /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
311 /// it will return [`None`].
313 /// [`last_os_error`]: Error::last_os_error
314 /// [`from_raw_os_error`]: Error::from_raw_os_error
319 /// use std::io::{Error, ErrorKind};
321 /// fn print_os_error(err: &Error) {
322 /// if let Some(raw_os_err) = err.raw_os_error() {
323 /// println!("raw OS error: {:?}", raw_os_err);
325 /// println!("Not an OS error");
330 /// // Will print "raw OS error: ...".
331 /// print_os_error(&Error::last_os_error());
332 /// // Will print "Not an OS error".
333 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn raw_os_error(&self) -> Option<i32> {
339 Repr::Os(i) => Some(i),
340 Repr::Custom(..) => None,
341 Repr::Simple(..) => None,
345 /// Returns a reference to the inner error wrapped by this error (if any).
347 /// If this [`Error`] was constructed via [`new`] then this function will
348 /// return [`Some`], otherwise it will return [`None`].
350 /// [`new`]: Error::new
355 /// use std::io::{Error, ErrorKind};
357 /// fn print_error(err: &Error) {
358 /// if let Some(inner_err) = err.get_ref() {
359 /// println!("Inner error: {:?}", inner_err);
361 /// println!("No inner error");
366 /// // Will print "No inner error".
367 /// print_error(&Error::last_os_error());
368 /// // Will print "Inner error: ...".
369 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
372 #[stable(feature = "io_error_inner", since = "1.3.0")]
373 pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
375 Repr::Os(..) => None,
376 Repr::Simple(..) => None,
377 Repr::Custom(ref c) => Some(&*c.error),
381 /// Returns a mutable reference to the inner error wrapped by this error
384 /// If this [`Error`] was constructed via [`new`] then this function will
385 /// return [`Some`], otherwise it will return [`None`].
387 /// [`new`]: Error::new
392 /// use std::io::{Error, ErrorKind};
393 /// use std::{error, fmt};
394 /// use std::fmt::Display;
402 /// fn new() -> MyError {
404 /// v: "oh no!".to_string()
408 /// fn change_message(&mut self, new_message: &str) {
409 /// self.v = new_message.to_string();
413 /// impl error::Error for MyError {}
415 /// impl Display for MyError {
416 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 /// write!(f, "MyError: {}", &self.v)
421 /// fn change_error(mut err: Error) -> Error {
422 /// if let Some(inner_err) = err.get_mut() {
423 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
428 /// fn print_error(err: &Error) {
429 /// if let Some(inner_err) = err.get_ref() {
430 /// println!("Inner error: {}", inner_err);
432 /// println!("No inner error");
437 /// // Will print "No inner error".
438 /// print_error(&change_error(Error::last_os_error()));
439 /// // Will print "Inner error: ...".
440 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
443 #[stable(feature = "io_error_inner", since = "1.3.0")]
444 pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
446 Repr::Os(..) => None,
447 Repr::Simple(..) => None,
448 Repr::Custom(ref mut c) => Some(&mut *c.error),
452 /// Consumes the `Error`, returning its inner error (if any).
454 /// If this [`Error`] was constructed via [`new`] then this function will
455 /// return [`Some`], otherwise it will return [`None`].
457 /// [`new`]: Error::new
462 /// use std::io::{Error, ErrorKind};
464 /// fn print_error(err: Error) {
465 /// if let Some(inner_err) = err.into_inner() {
466 /// println!("Inner error: {}", inner_err);
468 /// println!("No inner error");
473 /// // Will print "No inner error".
474 /// print_error(Error::last_os_error());
475 /// // Will print "Inner error: ...".
476 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
479 #[stable(feature = "io_error_inner", since = "1.3.0")]
480 pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
482 Repr::Os(..) => None,
483 Repr::Simple(..) => None,
484 Repr::Custom(c) => Some(c.error),
488 /// Returns the corresponding [`ErrorKind`] for this error.
493 /// use std::io::{Error, ErrorKind};
495 /// fn print_error(err: Error) {
496 /// println!("{:?}", err.kind());
500 /// // Will print "Other".
501 /// print_error(Error::last_os_error());
502 /// // Will print "AddrInUse".
503 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn kind(&self) -> ErrorKind {
509 Repr::Os(code) => sys::decode_error_kind(code),
510 Repr::Custom(ref c) => c.kind,
511 Repr::Simple(kind) => kind,
516 impl fmt::Debug for Repr {
517 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
519 Repr::Os(code) => fmt
521 .field("code", &code)
522 .field("kind", &sys::decode_error_kind(code))
523 .field("message", &sys::os::error_string(code))
525 Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
526 Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl fmt::Display for Error {
533 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
536 let detail = sys::os::error_string(code);
537 write!(fmt, "{} (os error {})", detail, code)
539 Repr::Custom(ref c) => c.error.fmt(fmt),
540 Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl error::Error for Error {
547 #[allow(deprecated, deprecated_in_future)]
548 fn description(&self) -> &str {
550 Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
551 Repr::Custom(ref c) => c.error.description(),
556 fn cause(&self) -> Option<&dyn error::Error> {
558 Repr::Os(..) => None,
559 Repr::Simple(..) => None,
560 Repr::Custom(ref c) => c.error.cause(),
564 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
566 Repr::Os(..) => None,
567 Repr::Simple(..) => None,
568 Repr::Custom(ref c) => c.error.source(),
573 fn _assert_error_is_sync_send() {
574 fn _is_sync_send<T: Sync + Send>() {}
575 _is_sync_send::<Error>();
580 use super::{Custom, Error, ErrorKind, Repr};
583 use crate::sys::decode_error_kind;
584 use crate::sys::os::error_string;
587 fn test_debug_error() {
589 let msg = error_string(code);
590 let kind = decode_error_kind(code);
592 repr: Repr::Custom(box Custom {
593 kind: ErrorKind::InvalidInput,
594 error: box Error { repr: super::Repr::Os(code) },
597 let expected = format!(
599 kind: InvalidInput, \
608 assert_eq!(format!("{:?}", err), expected);
612 fn test_downcasting() {
616 impl fmt::Display for TestError {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622 impl error::Error for TestError {}
624 // we have to call all of these UFCS style right now since method
625 // resolution won't implicitly drop the Send+Sync bounds
626 let mut err = Error::new(ErrorKind::Other, TestError);
627 assert!(err.get_ref().unwrap().is::<TestError>());
628 assert_eq!("asdf", err.get_ref().unwrap().to_string());
629 assert!(err.get_mut().unwrap().is::<TestError>());
630 let extracted = err.into_inner().unwrap();
631 extracted.downcast::<TestError>().unwrap();