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 {
211 fn from(kind: ErrorKind) -> Error {
213 repr: Repr::Simple(kind)
219 /// Creates a new I/O error from a known kind of error as well as an
220 /// arbitrary error payload.
222 /// This function is used to generically create I/O errors which do not
223 /// originate from the OS itself. The `error` argument is an arbitrary
224 /// payload which will be contained in this `Error`.
229 /// use std::io::{Error, ErrorKind};
231 /// // errors can be created from strings
232 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
234 /// // errors can also be created from other errors
235 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
237 #[stable(feature = "rust1", since = "1.0.0")]
238 pub fn new<E>(kind: ErrorKind, error: E) -> Error
239 where E: Into<Box<error::Error+Send+Sync>>
241 Self::_new(kind, error.into())
244 fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
246 repr: Repr::Custom(Box::new(Custom {
253 /// Returns an error representing the last OS error which occurred.
255 /// This function reads the value of `errno` for the target platform (e.g.
256 /// `GetLastError` on Windows) and will return a corresponding instance of
257 /// `Error` for the error code.
262 /// use std::io::Error;
264 /// println!("last OS error: {:?}", Error::last_os_error());
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn last_os_error() -> Error {
268 Error::from_raw_os_error(sys::os::errno() as i32)
271 /// Creates a new instance of an `Error` from a particular OS error code.
278 /// # if cfg!(target_os = "linux") {
281 /// let error = io::Error::from_raw_os_error(98);
282 /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
289 /// # if cfg!(windows) {
292 /// let error = io::Error::from_raw_os_error(10048);
293 /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn from_raw_os_error(code: i32) -> Error {
298 Error { repr: Repr::Os(code) }
301 /// Returns the OS error that this error represents (if any).
303 /// If this `Error` was constructed via `last_os_error` or
304 /// `from_raw_os_error`, then this function will return `Some`, otherwise
305 /// it will return `None`.
310 /// use std::io::{Error, ErrorKind};
312 /// fn print_os_error(err: &Error) {
313 /// if let Some(raw_os_err) = err.raw_os_error() {
314 /// println!("raw OS error: {:?}", raw_os_err);
316 /// println!("Not an OS error");
321 /// // Will print "raw OS error: ...".
322 /// print_os_error(&Error::last_os_error());
323 /// // Will print "Not an OS error".
324 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
327 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn raw_os_error(&self) -> Option<i32> {
330 Repr::Os(i) => Some(i),
331 Repr::Custom(..) => None,
332 Repr::Simple(..) => None,
336 /// Returns a reference to the inner error wrapped by this error (if any).
338 /// If this `Error` was constructed via `new` then this function will
339 /// return `Some`, otherwise it will return `None`.
344 /// use std::io::{Error, ErrorKind};
346 /// fn print_error(err: &Error) {
347 /// if let Some(inner_err) = err.get_ref() {
348 /// println!("Inner error: {:?}", inner_err);
350 /// println!("No inner error");
355 /// // Will print "No inner error".
356 /// print_error(&Error::last_os_error());
357 /// // Will print "Inner error: ...".
358 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
361 #[stable(feature = "io_error_inner", since = "1.3.0")]
362 pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
364 Repr::Os(..) => None,
365 Repr::Simple(..) => None,
366 Repr::Custom(ref c) => Some(&*c.error),
370 /// Returns a mutable reference to the inner error wrapped by this error
373 /// If this `Error` was constructed via `new` then this function will
374 /// return `Some`, otherwise it will return `None`.
379 /// use std::io::{Error, ErrorKind};
380 /// use std::{error, fmt};
381 /// use std::fmt::Display;
389 /// fn new() -> MyError {
391 /// v: "oh no!".to_string()
395 /// fn change_message(&mut self, new_message: &str) {
396 /// self.v = new_message.to_string();
400 /// impl error::Error for MyError {
401 /// fn description(&self) -> &str { &self.v }
404 /// impl Display for MyError {
405 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406 /// write!(f, "MyError: {}", &self.v)
410 /// fn change_error(mut err: Error) -> Error {
411 /// if let Some(inner_err) = err.get_mut() {
412 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
417 /// fn print_error(err: &Error) {
418 /// if let Some(inner_err) = err.get_ref() {
419 /// println!("Inner error: {}", inner_err);
421 /// println!("No inner error");
426 /// // Will print "No inner error".
427 /// print_error(&change_error(Error::last_os_error()));
428 /// // Will print "Inner error: ...".
429 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
432 #[stable(feature = "io_error_inner", since = "1.3.0")]
433 pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
435 Repr::Os(..) => None,
436 Repr::Simple(..) => None,
437 Repr::Custom(ref mut c) => Some(&mut *c.error),
441 /// Consumes the `Error`, returning its inner error (if any).
443 /// If this `Error` was constructed via `new` then this function will
444 /// return `Some`, otherwise it will return `None`.
449 /// use std::io::{Error, ErrorKind};
451 /// fn print_error(err: Error) {
452 /// if let Some(inner_err) = err.into_inner() {
453 /// println!("Inner error: {}", inner_err);
455 /// println!("No inner error");
460 /// // Will print "No inner error".
461 /// print_error(Error::last_os_error());
462 /// // Will print "Inner error: ...".
463 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
466 #[stable(feature = "io_error_inner", since = "1.3.0")]
467 pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
469 Repr::Os(..) => None,
470 Repr::Simple(..) => None,
471 Repr::Custom(c) => Some(c.error)
475 /// Returns the corresponding `ErrorKind` for this error.
480 /// use std::io::{Error, ErrorKind};
482 /// fn print_error(err: Error) {
483 /// println!("{:?}", err.kind());
487 /// // Will print "No inner error".
488 /// print_error(Error::last_os_error());
489 /// // Will print "Inner error: ...".
490 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn kind(&self) -> ErrorKind {
496 Repr::Os(code) => sys::decode_error_kind(code),
497 Repr::Custom(ref c) => c.kind,
498 Repr::Simple(kind) => kind,
503 impl fmt::Debug for Repr {
504 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
506 Repr::Os(ref code) =>
507 fmt.debug_struct("Os").field("code", code)
508 .field("message", &sys::os::error_string(*code)).finish(),
509 Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
510 Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl fmt::Display for Error {
517 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
520 let detail = sys::os::error_string(code);
521 write!(fmt, "{} (os error {})", detail, code)
523 Repr::Custom(ref c) => c.error.fmt(fmt),
524 Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl error::Error for Error {
531 fn description(&self) -> &str {
533 Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
534 Repr::Custom(ref c) => c.error.description(),
538 fn cause(&self) -> Option<&error::Error> {
540 Repr::Os(..) => None,
541 Repr::Simple(..) => None,
542 Repr::Custom(ref c) => c.error.cause(),
547 fn _assert_error_is_sync_send() {
548 fn _is_sync_send<T: Sync+Send>() {}
549 _is_sync_send::<Error>();
554 use super::{Error, ErrorKind};
557 use sys::os::error_string;
560 fn test_debug_error() {
562 let msg = error_string(code);
563 let err = Error { repr: super::Repr::Os(code) };
564 let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
565 assert_eq!(format!("{:?}", err), expected);
569 fn test_downcasting() {
573 impl fmt::Display for TestError {
574 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
579 impl error::Error for TestError {
580 fn description(&self) -> &str {
585 // we have to call all of these UFCS style right now since method
586 // resolution won't implicitly drop the Send+Sync bounds
587 let mut err = Error::new(ErrorKind::Other, TestError);
588 assert!(err.get_ref().unwrap().is::<TestError>());
589 assert_eq!("asdf", err.get_ref().unwrap().description());
590 assert!(err.get_mut().unwrap().is::<TestError>());
591 let extracted = err.into_inner().unwrap();
592 extracted.downcast::<TestError>().unwrap();