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