]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/error.rs
6515a5540eeb91f048922b4f36f21b4370fbe89f
[rust.git] / src / libstd / io / error.rs
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.
4 //
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.
10
11 use error;
12 use fmt;
13 use result;
14 use sys;
15 use convert::From;
16
17 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
18 /// operations.
19 ///
20 /// This type is broadly used across [`std::io`] for any operation which may
21 /// produce an error.
22 ///
23 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
24 /// is otherwise a direct mapping to [`Result`].
25 ///
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`][`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`][`Result`].
31 ///
32 /// [`std::io`]: ../io/index.html
33 /// [`io::Error`]: ../io/struct.Error.html
34 /// [`Result`]: ../result/enum.Result.html
35 ///
36 /// # Examples
37 ///
38 /// A convenience function that bubbles an `io::Result` to its caller:
39 ///
40 /// ```
41 /// use std::io;
42 ///
43 /// fn get_string() -> io::Result<String> {
44 ///     let mut buffer = String::new();
45 ///
46 ///     io::stdin().read_line(&mut buffer)?;
47 ///
48 ///     Ok(buffer)
49 /// }
50 /// ```
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub type Result<T> = result::Result<T, Error>;
53
54 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
55 /// associated traits.
56 ///
57 /// Errors mostly originate from the underlying OS, but custom instances of
58 /// `Error` can be created with crafted error messages and a particular value of
59 /// [`ErrorKind`].
60 ///
61 /// [`Read`]: ../io/trait.Read.html
62 /// [`Write`]: ../io/trait.Write.html
63 /// [`Seek`]: ../io/trait.Seek.html
64 /// [`ErrorKind`]: enum.ErrorKind.html
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct Error {
67     repr: Repr,
68 }
69
70 #[stable(feature = "rust1", since = "1.0.0")]
71 impl fmt::Debug for Error {
72     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73         fmt::Debug::fmt(&self.repr, f)
74     }
75 }
76
77 enum Repr {
78     Os(i32),
79     Simple(ErrorKind),
80     Custom(Box<Custom>),
81 }
82
83 #[derive(Debug)]
84 struct Custom {
85     kind: ErrorKind,
86     error: Box<dyn error::Error+Send+Sync>,
87 }
88
89 /// A list specifying general categories of I/O error.
90 ///
91 /// This list is intended to grow over time and it is not recommended to
92 /// exhaustively match against it.
93 ///
94 /// It is used with the [`io::Error`] type.
95 ///
96 /// [`io::Error`]: struct.Error.html
97 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[allow(deprecated)]
100 #[non_exhaustive]
101 pub enum ErrorKind {
102     /// An entity was not found, often a file.
103     #[stable(feature = "rust1", since = "1.0.0")]
104     NotFound,
105     /// The operation lacked the necessary privileges to complete.
106     #[stable(feature = "rust1", since = "1.0.0")]
107     PermissionDenied,
108     /// The connection was refused by the remote server.
109     #[stable(feature = "rust1", since = "1.0.0")]
110     ConnectionRefused,
111     /// The connection was reset by the remote server.
112     #[stable(feature = "rust1", since = "1.0.0")]
113     ConnectionReset,
114     /// The connection was aborted (terminated) by the remote server.
115     #[stable(feature = "rust1", since = "1.0.0")]
116     ConnectionAborted,
117     /// The network operation failed because it was not connected yet.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     NotConnected,
120     /// A socket address could not be bound because the address is already in
121     /// use elsewhere.
122     #[stable(feature = "rust1", since = "1.0.0")]
123     AddrInUse,
124     /// A nonexistent interface was requested or the requested address was not
125     /// local.
126     #[stable(feature = "rust1", since = "1.0.0")]
127     AddrNotAvailable,
128     /// The operation failed because a pipe was closed.
129     #[stable(feature = "rust1", since = "1.0.0")]
130     BrokenPipe,
131     /// An entity already exists, often a file.
132     #[stable(feature = "rust1", since = "1.0.0")]
133     AlreadyExists,
134     /// The operation needs to block to complete, but the blocking operation was
135     /// requested to not occur.
136     #[stable(feature = "rust1", since = "1.0.0")]
137     WouldBlock,
138     /// A parameter was incorrect.
139     #[stable(feature = "rust1", since = "1.0.0")]
140     InvalidInput,
141     /// Data not valid for the operation were encountered.
142     ///
143     /// Unlike [`InvalidInput`], this typically means that the operation
144     /// parameters were valid, however the error was caused by malformed
145     /// input data.
146     ///
147     /// For example, a function that reads a file into a string will error with
148     /// `InvalidData` if the file's contents are not valid UTF-8.
149     ///
150     /// [`InvalidInput`]: #variant.InvalidInput
151     #[stable(feature = "io_invalid_data", since = "1.2.0")]
152     InvalidData,
153     /// The I/O operation's timeout expired, causing it to be canceled.
154     #[stable(feature = "rust1", since = "1.0.0")]
155     TimedOut,
156     /// An error returned when an operation could not be completed because a
157     /// call to [`write`] returned [`Ok(0)`].
158     ///
159     /// This typically means that an operation could only succeed if it wrote a
160     /// particular number of bytes but only a smaller number of bytes could be
161     /// written.
162     ///
163     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
164     /// [`Ok(0)`]: ../../std/io/type.Result.html
165     #[stable(feature = "rust1", since = "1.0.0")]
166     WriteZero,
167     /// This operation was interrupted.
168     ///
169     /// Interrupted operations can typically be retried.
170     #[stable(feature = "rust1", since = "1.0.0")]
171     Interrupted,
172     /// Any I/O error not part of this list.
173     #[stable(feature = "rust1", since = "1.0.0")]
174     Other,
175
176     /// An error returned when an operation could not be completed because an
177     /// "end of file" was reached prematurely.
178     ///
179     /// This typically means that an operation could only succeed if it read a
180     /// particular number of bytes but only a smaller number of bytes could be
181     /// read.
182     #[stable(feature = "read_exact", since = "1.6.0")]
183     UnexpectedEof,
184 }
185
186 impl ErrorKind {
187     fn as_str(&self) -> &'static str {
188         match *self {
189             ErrorKind::NotFound => "entity not found",
190             ErrorKind::PermissionDenied => "permission denied",
191             ErrorKind::ConnectionRefused => "connection refused",
192             ErrorKind::ConnectionReset => "connection reset",
193             ErrorKind::ConnectionAborted => "connection aborted",
194             ErrorKind::NotConnected => "not connected",
195             ErrorKind::AddrInUse => "address in use",
196             ErrorKind::AddrNotAvailable => "address not available",
197             ErrorKind::BrokenPipe => "broken pipe",
198             ErrorKind::AlreadyExists => "entity already exists",
199             ErrorKind::WouldBlock => "operation would block",
200             ErrorKind::InvalidInput => "invalid input parameter",
201             ErrorKind::InvalidData => "invalid data",
202             ErrorKind::TimedOut => "timed out",
203             ErrorKind::WriteZero => "write zero",
204             ErrorKind::Interrupted => "operation interrupted",
205             ErrorKind::Other => "other os error",
206             ErrorKind::UnexpectedEof => "unexpected end of file",
207         }
208     }
209 }
210
211 /// Intended for use for errors not exposed to the user, where allocating onto
212 /// the heap (for normal construction via Error::new) is too costly.
213 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
214 impl From<ErrorKind> for Error {
215     /// Converts a [`ErrorKind`] into a [`Error`].
216     ///
217     /// This conversion allocates a new error with a simple representation of error kind.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// use std::io::{Error, ErrorKind};
223     ///
224     /// let not_found = ErrorKind::NotFound;
225     /// let error = Error::from(not_found);
226     /// assert_eq!("entity not found", format!("{}", error));
227     /// ```
228     #[inline]
229     fn from(kind: ErrorKind) -> Error {
230         Error {
231             repr: Repr::Simple(kind)
232         }
233     }
234 }
235
236 impl Error {
237     /// Creates a new I/O error from a known kind of error as well as an
238     /// arbitrary error payload.
239     ///
240     /// This function is used to generically create I/O errors which do not
241     /// originate from the OS itself. The `error` argument is an arbitrary
242     /// payload which will be contained in this `Error`.
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use std::io::{Error, ErrorKind};
248     ///
249     /// // errors can be created from strings
250     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
251     ///
252     /// // errors can also be created from other errors
253     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
254     /// ```
255     #[stable(feature = "rust1", since = "1.0.0")]
256     pub fn new<E>(kind: ErrorKind, error: E) -> Error
257         where E: Into<Box<dyn error::Error+Send+Sync>>
258     {
259         Self::_new(kind, error.into())
260     }
261
262     fn _new(kind: ErrorKind, error: Box<dyn error::Error+Send+Sync>) -> Error {
263         Error {
264             repr: Repr::Custom(Box::new(Custom {
265                 kind,
266                 error,
267             }))
268         }
269     }
270
271     /// Returns an error representing the last OS error which occurred.
272     ///
273     /// This function reads the value of `errno` for the target platform (e.g.
274     /// `GetLastError` on Windows) and will return a corresponding instance of
275     /// `Error` for the error code.
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::io::Error;
281     ///
282     /// println!("last OS error: {:?}", Error::last_os_error());
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn last_os_error() -> Error {
286         Error::from_raw_os_error(sys::os::errno() as i32)
287     }
288
289     /// Creates a new instance of an `Error` from a particular OS error code.
290     ///
291     /// # Examples
292     ///
293     /// On Linux:
294     ///
295     /// ```
296     /// # if cfg!(target_os = "linux") {
297     /// use std::io;
298     ///
299     /// let error = io::Error::from_raw_os_error(22);
300     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
301     /// # }
302     /// ```
303     ///
304     /// On Windows:
305     ///
306     /// ```
307     /// # if cfg!(windows) {
308     /// use std::io;
309     ///
310     /// let error = io::Error::from_raw_os_error(10022);
311     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
312     /// # }
313     /// ```
314     #[stable(feature = "rust1", since = "1.0.0")]
315     pub fn from_raw_os_error(code: i32) -> Error {
316         Error { repr: Repr::Os(code) }
317     }
318
319     /// Returns the OS error that this error represents (if any).
320     ///
321     /// If this `Error` was constructed via `last_os_error` or
322     /// `from_raw_os_error`, then this function will return `Some`, otherwise
323     /// it will return `None`.
324     ///
325     /// # Examples
326     ///
327     /// ```
328     /// use std::io::{Error, ErrorKind};
329     ///
330     /// fn print_os_error(err: &Error) {
331     ///     if let Some(raw_os_err) = err.raw_os_error() {
332     ///         println!("raw OS error: {:?}", raw_os_err);
333     ///     } else {
334     ///         println!("Not an OS error");
335     ///     }
336     /// }
337     ///
338     /// fn main() {
339     ///     // Will print "raw OS error: ...".
340     ///     print_os_error(&Error::last_os_error());
341     ///     // Will print "Not an OS error".
342     ///     print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
343     /// }
344     /// ```
345     #[stable(feature = "rust1", since = "1.0.0")]
346     pub fn raw_os_error(&self) -> Option<i32> {
347         match self.repr {
348             Repr::Os(i) => Some(i),
349             Repr::Custom(..) => None,
350             Repr::Simple(..) => None,
351         }
352     }
353
354     /// Returns a reference to the inner error wrapped by this error (if any).
355     ///
356     /// If this `Error` was constructed via `new` then this function will
357     /// return `Some`, otherwise it will return `None`.
358     ///
359     /// # Examples
360     ///
361     /// ```
362     /// use std::io::{Error, ErrorKind};
363     ///
364     /// fn print_error(err: &Error) {
365     ///     if let Some(inner_err) = err.get_ref() {
366     ///         println!("Inner error: {:?}", inner_err);
367     ///     } else {
368     ///         println!("No inner error");
369     ///     }
370     /// }
371     ///
372     /// fn main() {
373     ///     // Will print "No inner error".
374     ///     print_error(&Error::last_os_error());
375     ///     // Will print "Inner error: ...".
376     ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
377     /// }
378     /// ```
379     #[stable(feature = "io_error_inner", since = "1.3.0")]
380     pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> {
381         match self.repr {
382             Repr::Os(..) => None,
383             Repr::Simple(..) => None,
384             Repr::Custom(ref c) => Some(&*c.error),
385         }
386     }
387
388     /// Returns a mutable reference to the inner error wrapped by this error
389     /// (if any).
390     ///
391     /// If this `Error` was constructed via `new` then this function will
392     /// return `Some`, otherwise it will return `None`.
393     ///
394     /// # Examples
395     ///
396     /// ```
397     /// use std::io::{Error, ErrorKind};
398     /// use std::{error, fmt};
399     /// use std::fmt::Display;
400     ///
401     /// #[derive(Debug)]
402     /// struct MyError {
403     ///     v: String,
404     /// }
405     ///
406     /// impl MyError {
407     ///     fn new() -> MyError {
408     ///         MyError {
409     ///             v: "oh no!".to_string()
410     ///         }
411     ///     }
412     ///
413     ///     fn change_message(&mut self, new_message: &str) {
414     ///         self.v = new_message.to_string();
415     ///     }
416     /// }
417     ///
418     /// impl error::Error for MyError {
419     ///     fn description(&self) -> &str { &self.v }
420     /// }
421     ///
422     /// impl Display for MyError {
423     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424     ///         write!(f, "MyError: {}", &self.v)
425     ///     }
426     /// }
427     ///
428     /// fn change_error(mut err: Error) -> Error {
429     ///     if let Some(inner_err) = err.get_mut() {
430     ///         inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
431     ///     }
432     ///     err
433     /// }
434     ///
435     /// fn print_error(err: &Error) {
436     ///     if let Some(inner_err) = err.get_ref() {
437     ///         println!("Inner error: {}", inner_err);
438     ///     } else {
439     ///         println!("No inner error");
440     ///     }
441     /// }
442     ///
443     /// fn main() {
444     ///     // Will print "No inner error".
445     ///     print_error(&change_error(Error::last_os_error()));
446     ///     // Will print "Inner error: ...".
447     ///     print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
448     /// }
449     /// ```
450     #[stable(feature = "io_error_inner", since = "1.3.0")]
451     pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> {
452         match self.repr {
453             Repr::Os(..) => None,
454             Repr::Simple(..) => None,
455             Repr::Custom(ref mut c) => Some(&mut *c.error),
456         }
457     }
458
459     /// Consumes the `Error`, returning its inner error (if any).
460     ///
461     /// If this `Error` was constructed via `new` then this function will
462     /// return `Some`, otherwise it will return `None`.
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// use std::io::{Error, ErrorKind};
468     ///
469     /// fn print_error(err: Error) {
470     ///     if let Some(inner_err) = err.into_inner() {
471     ///         println!("Inner error: {}", inner_err);
472     ///     } else {
473     ///         println!("No inner error");
474     ///     }
475     /// }
476     ///
477     /// fn main() {
478     ///     // Will print "No inner error".
479     ///     print_error(Error::last_os_error());
480     ///     // Will print "Inner error: ...".
481     ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
482     /// }
483     /// ```
484     #[stable(feature = "io_error_inner", since = "1.3.0")]
485     pub fn into_inner(self) -> Option<Box<dyn error::Error+Send+Sync>> {
486         match self.repr {
487             Repr::Os(..) => None,
488             Repr::Simple(..) => None,
489             Repr::Custom(c) => Some(c.error)
490         }
491     }
492
493     /// Returns the corresponding `ErrorKind` for this error.
494     ///
495     /// # Examples
496     ///
497     /// ```
498     /// use std::io::{Error, ErrorKind};
499     ///
500     /// fn print_error(err: Error) {
501     ///     println!("{:?}", err.kind());
502     /// }
503     ///
504     /// fn main() {
505     ///     // Will print "No inner error".
506     ///     print_error(Error::last_os_error());
507     ///     // Will print "Inner error: ...".
508     ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
509     /// }
510     /// ```
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn kind(&self) -> ErrorKind {
513         match self.repr {
514             Repr::Os(code) => sys::decode_error_kind(code),
515             Repr::Custom(ref c) => c.kind,
516             Repr::Simple(kind) => kind,
517         }
518     }
519 }
520
521 impl fmt::Debug for Repr {
522     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
523         match *self {
524             Repr::Os(code) =>
525                 fmt.debug_struct("Os")
526                     .field("code", &code)
527                     .field("kind", &sys::decode_error_kind(code))
528                     .field("message", &sys::os::error_string(code)).finish(),
529             Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
530             Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
531         }
532     }
533 }
534
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl fmt::Display for Error {
537     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
538         match self.repr {
539             Repr::Os(code) => {
540                 let detail = sys::os::error_string(code);
541                 write!(fmt, "{} (os error {})", detail, code)
542             }
543             Repr::Custom(ref c) => c.error.fmt(fmt),
544             Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
545         }
546     }
547 }
548
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl error::Error for Error {
551     fn description(&self) -> &str {
552         match self.repr {
553             Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
554             Repr::Custom(ref c) => c.error.description(),
555         }
556     }
557
558     fn cause(&self) -> Option<&dyn error::Error> {
559         match self.repr {
560             Repr::Os(..) => None,
561             Repr::Simple(..) => None,
562             Repr::Custom(ref c) => c.error.cause(),
563         }
564     }
565 }
566
567 fn _assert_error_is_sync_send() {
568     fn _is_sync_send<T: Sync+Send>() {}
569     _is_sync_send::<Error>();
570 }
571
572 #[cfg(test)]
573 mod test {
574     use super::{Error, ErrorKind, Repr, Custom};
575     use error;
576     use fmt;
577     use sys::os::error_string;
578     use sys::decode_error_kind;
579
580     #[test]
581     fn test_debug_error() {
582         let code = 6;
583         let msg = error_string(code);
584         let kind = decode_error_kind(code);
585         let err = Error {
586             repr: Repr::Custom(box Custom {
587                 kind: ErrorKind::InvalidInput,
588                 error: box Error {
589                     repr: super::Repr::Os(code)
590                 },
591             })
592         };
593         let expected = format!(
594             "Custom {{ \
595                 kind: InvalidInput, \
596                 error: Os {{ \
597                     code: {:?}, \
598                     kind: {:?}, \
599                     message: {:?} \
600                 }} \
601             }}",
602             code, kind, msg
603         );
604         assert_eq!(format!("{:?}", err), expected);
605     }
606
607     #[test]
608     fn test_downcasting() {
609         #[derive(Debug)]
610         struct TestError;
611
612         impl fmt::Display for TestError {
613             fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
614                 Ok(())
615             }
616         }
617
618         impl error::Error for TestError {
619             fn description(&self) -> &str {
620                 "asdf"
621             }
622         }
623
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().description());
629         assert!(err.get_mut().unwrap().is::<TestError>());
630         let extracted = err.into_inner().unwrap();
631         extracted.downcast::<TestError>().unwrap();
632     }
633 }