1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
17 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
20 /// This type is broadly used across `std::io` for any operation which may
23 /// This typedef is generally used to avoid writing out `io::Error` directly and
24 /// is otherwise a direct mapping to `Result`.
26 /// While usual Rust style is to import types directly, aliases of `Result`
27 /// often are not, to make it easier to distinguish between them. `Result` is
28 /// generally assumed to be `std::result::Result`, and so users of this alias
29 /// will generally use `io::Result` instead of shadowing the prelude's import
30 /// of `std::result::Result`.
34 /// A convenience function that bubbles an `io::Result` to its caller:
39 /// fn get_string() -> io::Result<String> {
40 /// let mut buffer = String::new();
42 /// io::stdin().read_line(&mut buffer)?;
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub type Result<T> = result::Result<T, Error>;
50 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
51 /// associated traits.
53 /// Errors mostly originate from the underlying OS, but custom instances of
54 /// `Error` can be created with crafted error messages and a particular value of
57 /// [`ErrorKind`]: enum.ErrorKind.html
59 #[stable(feature = "rust1", since = "1.0.0")]
73 error: Box<error::Error+Send+Sync>,
76 /// A list specifying general categories of I/O error.
78 /// This list is intended to grow over time and it is not recommended to
79 /// exhaustively match against it.
81 /// It is used with the [`io::Error`] type.
83 /// [`io::Error`]: struct.Error.html
84 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
85 #[stable(feature = "rust1", since = "1.0.0")]
88 /// An entity was not found, often a file.
89 #[stable(feature = "rust1", since = "1.0.0")]
91 /// The operation lacked the necessary privileges to complete.
92 #[stable(feature = "rust1", since = "1.0.0")]
94 /// The connection was refused by the remote server.
95 #[stable(feature = "rust1", since = "1.0.0")]
97 /// The connection was reset by the remote server.
98 #[stable(feature = "rust1", since = "1.0.0")]
100 /// The connection was aborted (terminated) by the remote server.
101 #[stable(feature = "rust1", since = "1.0.0")]
103 /// The network operation failed because it was not connected yet.
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// A socket address could not be bound because the address is already in
108 #[stable(feature = "rust1", since = "1.0.0")]
110 /// A nonexistent interface was requested or the requested address was not
112 #[stable(feature = "rust1", since = "1.0.0")]
114 /// The operation failed because a pipe was closed.
115 #[stable(feature = "rust1", since = "1.0.0")]
117 /// An entity already exists, often a file.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 /// The operation needs to block to complete, but the blocking operation was
121 /// requested to not occur.
122 #[stable(feature = "rust1", since = "1.0.0")]
124 /// A parameter was incorrect.
125 #[stable(feature = "rust1", since = "1.0.0")]
127 /// Data not valid for the operation were encountered.
129 /// Unlike [`InvalidInput`], this typically means that the operation
130 /// parameters were valid, however the error was caused by malformed
133 /// For example, a function that reads a file into a string will error with
134 /// `InvalidData` if the file's contents are not valid UTF-8.
136 /// [`InvalidInput`]: #variant.InvalidInput
137 #[stable(feature = "io_invalid_data", since = "1.2.0")]
139 /// The I/O operation's timeout expired, causing it to be canceled.
140 #[stable(feature = "rust1", since = "1.0.0")]
142 /// An error returned when an operation could not be completed because a
143 /// call to [`write`] returned [`Ok(0)`].
145 /// This typically means that an operation could only succeed if it wrote a
146 /// particular number of bytes but only a smaller number of bytes could be
149 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
150 /// [`Ok(0)`]: ../../std/io/type.Result.html
151 #[stable(feature = "rust1", since = "1.0.0")]
153 /// This operation was interrupted.
155 /// Interrupted operations can typically be retried.
156 #[stable(feature = "rust1", since = "1.0.0")]
158 /// Any I/O error not part of this list.
159 #[stable(feature = "rust1", since = "1.0.0")]
162 /// An error returned when an operation could not be completed because an
163 /// "end of file" was reached prematurely.
165 /// This typically means that an operation could only succeed if it read a
166 /// particular number of bytes but only a smaller number of bytes could be
168 #[stable(feature = "read_exact", since = "1.6.0")]
171 /// A marker variant that tells the compiler that users of this enum cannot
172 /// match it exhaustively.
173 #[unstable(feature = "io_error_internals",
174 reason = "better expressed through extensible enums that this \
175 enum cannot be exhaustively matched against",
182 fn as_str(&self) -> &'static str {
184 ErrorKind::NotFound => "entity not found",
185 ErrorKind::PermissionDenied => "permission denied",
186 ErrorKind::ConnectionRefused => "connection refused",
187 ErrorKind::ConnectionReset => "connection reset",
188 ErrorKind::ConnectionAborted => "connection aborted",
189 ErrorKind::NotConnected => "not connected",
190 ErrorKind::AddrInUse => "address in use",
191 ErrorKind::AddrNotAvailable => "address not available",
192 ErrorKind::BrokenPipe => "broken pipe",
193 ErrorKind::AlreadyExists => "entity already exists",
194 ErrorKind::WouldBlock => "operation would block",
195 ErrorKind::InvalidInput => "invalid input parameter",
196 ErrorKind::InvalidData => "invalid data",
197 ErrorKind::TimedOut => "timed out",
198 ErrorKind::WriteZero => "write zero",
199 ErrorKind::Interrupted => "operation interrupted",
200 ErrorKind::Other => "other os error",
201 ErrorKind::UnexpectedEof => "unexpected end of file",
202 ErrorKind::__Nonexhaustive => unreachable!()
207 /// Intended for use for errors not exposed to the user, where allocating onto
208 /// the heap (for normal construction via Error::new) is too costly.
209 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
210 impl From<ErrorKind> for Error {
212 fn from(kind: ErrorKind) -> Error {
214 repr: Repr::Simple(kind)
220 /// Creates a new I/O error from a known kind of error as well as an
221 /// arbitrary error payload.
223 /// This function is used to generically create I/O errors which do not
224 /// originate from the OS itself. The `error` argument is an arbitrary
225 /// payload which will be contained in this `Error`.
230 /// use std::io::{Error, ErrorKind};
232 /// // errors can be created from strings
233 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
235 /// // errors can also be created from other errors
236 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn new<E>(kind: ErrorKind, error: E) -> Error
240 where E: Into<Box<error::Error+Send+Sync>>
242 Self::_new(kind, error.into())
245 fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
247 repr: Repr::Custom(Box::new(Custom {
254 /// Returns an error representing the last OS error which occurred.
256 /// This function reads the value of `errno` for the target platform (e.g.
257 /// `GetLastError` on Windows) and will return a corresponding instance of
258 /// `Error` for the error code.
263 /// use std::io::Error;
265 /// println!("last OS error: {:?}", Error::last_os_error());
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn last_os_error() -> Error {
269 Error::from_raw_os_error(sys::os::errno() as i32)
272 /// Creates a new instance of an `Error` from a particular OS error code.
279 /// # if cfg!(target_os = "linux") {
282 /// let error = io::Error::from_raw_os_error(98);
283 /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
290 /// # if cfg!(windows) {
293 /// let error = io::Error::from_raw_os_error(10048);
294 /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn from_raw_os_error(code: i32) -> Error {
299 Error { repr: Repr::Os(code) }
302 /// Returns the OS error that this error represents (if any).
304 /// If this `Error` was constructed via `last_os_error` or
305 /// `from_raw_os_error`, then this function will return `Some`, otherwise
306 /// it will return `None`.
311 /// use std::io::{Error, ErrorKind};
313 /// fn print_os_error(err: &Error) {
314 /// if let Some(raw_os_err) = err.raw_os_error() {
315 /// println!("raw OS error: {:?}", raw_os_err);
317 /// println!("Not an OS error");
322 /// // Will print "raw OS error: ...".
323 /// print_os_error(&Error::last_os_error());
324 /// // Will print "Not an OS error".
325 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub fn raw_os_error(&self) -> Option<i32> {
331 Repr::Os(i) => Some(i),
332 Repr::Custom(..) => None,
333 Repr::Simple(..) => None,
337 /// Returns a reference to the inner error wrapped by this error (if any).
339 /// If this `Error` was constructed via `new` then this function will
340 /// return `Some`, otherwise it will return `None`.
345 /// use std::io::{Error, ErrorKind};
347 /// fn print_error(err: &Error) {
348 /// if let Some(inner_err) = err.get_ref() {
349 /// println!("Inner error: {:?}", inner_err);
351 /// println!("No inner error");
356 /// // Will print "No inner error".
357 /// print_error(&Error::last_os_error());
358 /// // Will print "Inner error: ...".
359 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
362 #[stable(feature = "io_error_inner", since = "1.3.0")]
363 pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
365 Repr::Os(..) => None,
366 Repr::Simple(..) => None,
367 Repr::Custom(ref c) => Some(&*c.error),
371 /// Returns a mutable reference to the inner error wrapped by this error
374 /// If this `Error` was constructed via `new` then this function will
375 /// return `Some`, otherwise it will return `None`.
380 /// use std::io::{Error, ErrorKind};
381 /// use std::{error, fmt};
382 /// use std::fmt::Display;
390 /// fn new() -> MyError {
392 /// v: "oh no!".to_string()
396 /// fn change_message(&mut self, new_message: &str) {
397 /// self.v = new_message.to_string();
401 /// impl error::Error for MyError {
402 /// fn description(&self) -> &str { &self.v }
405 /// impl Display for MyError {
406 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407 /// write!(f, "MyError: {}", &self.v)
411 /// fn change_error(mut err: Error) -> Error {
412 /// if let Some(inner_err) = err.get_mut() {
413 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
418 /// fn print_error(err: &Error) {
419 /// if let Some(inner_err) = err.get_ref() {
420 /// println!("Inner error: {}", inner_err);
422 /// println!("No inner error");
427 /// // Will print "No inner error".
428 /// print_error(&change_error(Error::last_os_error()));
429 /// // Will print "Inner error: ...".
430 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
433 #[stable(feature = "io_error_inner", since = "1.3.0")]
434 pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
436 Repr::Os(..) => None,
437 Repr::Simple(..) => None,
438 Repr::Custom(ref mut c) => Some(&mut *c.error),
442 /// Consumes the `Error`, returning its inner error (if any).
444 /// If this `Error` was constructed via `new` then this function will
445 /// return `Some`, otherwise it will return `None`.
450 /// use std::io::{Error, ErrorKind};
452 /// fn print_error(err: Error) {
453 /// if let Some(inner_err) = err.into_inner() {
454 /// println!("Inner error: {}", inner_err);
456 /// println!("No inner error");
461 /// // Will print "No inner error".
462 /// print_error(Error::last_os_error());
463 /// // Will print "Inner error: ...".
464 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
467 #[stable(feature = "io_error_inner", since = "1.3.0")]
468 pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
470 Repr::Os(..) => None,
471 Repr::Simple(..) => None,
472 Repr::Custom(c) => Some(c.error)
476 /// Returns the corresponding `ErrorKind` for this error.
481 /// use std::io::{Error, ErrorKind};
483 /// fn print_error(err: Error) {
484 /// println!("{:?}", err.kind());
488 /// // Will print "No inner error".
489 /// print_error(Error::last_os_error());
490 /// // Will print "Inner error: ...".
491 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn kind(&self) -> ErrorKind {
497 Repr::Os(code) => sys::decode_error_kind(code),
498 Repr::Custom(ref c) => c.kind,
499 Repr::Simple(kind) => kind,
504 impl fmt::Debug for Repr {
505 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
507 Repr::Os(ref code) =>
508 fmt.debug_struct("Os").field("code", code)
509 .field("message", &sys::os::error_string(*code)).finish(),
510 Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
511 Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl fmt::Display for Error {
518 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
521 let detail = sys::os::error_string(code);
522 write!(fmt, "{} (os error {})", detail, code)
524 Repr::Custom(ref c) => c.error.fmt(fmt),
525 Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl error::Error for Error {
532 fn description(&self) -> &str {
534 Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
535 Repr::Custom(ref c) => c.error.description(),
539 fn cause(&self) -> Option<&error::Error> {
541 Repr::Os(..) => None,
542 Repr::Simple(..) => None,
543 Repr::Custom(ref c) => c.error.cause(),
548 fn _assert_error_is_sync_send() {
549 fn _is_sync_send<T: Sync+Send>() {}
550 _is_sync_send::<Error>();
555 use super::{Error, ErrorKind};
558 use sys::os::error_string;
561 fn test_debug_error() {
563 let msg = error_string(code);
564 let err = Error { repr: super::Repr::Os(code) };
565 let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
566 assert_eq!(format!("{:?}", err), expected);
570 fn test_downcasting() {
574 impl fmt::Display for TestError {
575 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
580 impl error::Error for TestError {
581 fn description(&self) -> &str {
586 // we have to call all of these UFCS style right now since method
587 // resolution won't implicitly drop the Send+Sync bounds
588 let mut err = Error::new(ErrorKind::Other, TestError);
589 assert!(err.get_ref().unwrap().is::<TestError>());
590 assert_eq!("asdf", err.get_ref().unwrap().description());
591 assert!(err.get_mut().unwrap().is::<TestError>());
592 let extracted = err.into_inner().unwrap();
593 extracted.downcast::<TestError>().unwrap();