1 // Copyright 2012-2014 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.
11 //! Error handling with the `Result` type
13 //! `Result<T>` is the type used for returning and propagating
14 //! errors. It is an enum with the variants, `Ok(T)`, representing
15 //! success and containing a value, and `Err(E)`, representing error
16 //! and containing an error value.
19 //! enum Result<T, E> {
25 //! Functions return `Result` whenever errors are expected and
26 //! recoverable. In the `std` crate `Result` is most prominently used
27 //! for [I/O](../../std/io/index.html).
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
34 //! enum Version { Version1, Version2 }
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //! if header.len() < 1 {
38 //! return Err("invalid header length");
41 //! 1 => Ok(Version1),
42 //! 2 => Ok(Version2),
43 //! _ => Err("invalid version")
47 //! let version = parse_version(&[1, 2, 3, 4]);
50 //! println!("working with version: {}", v);
53 //! println!("error parsing header: {}", e);
58 //! Pattern matching on `Result`s is clear and straightforward for
59 //! simple cases, but `Result` comes with some convenience methods
60 //! that make working it more succinct.
63 //! let good_result: Result<int, int> = Ok(10);
64 //! let bad_result: Result<int, int> = Err(10);
66 //! // The `is_ok` and `is_err` methods do what they say.
67 //! assert!(good_result.is_ok() && !good_result.is_err());
68 //! assert!(bad_result.is_err() && !bad_result.is_ok());
70 //! // `map` consumes the `Result` and produces another.
71 //! let good_result: Result<int, int> = good_result.map(|i| i + 1);
72 //! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
74 //! // Use `and_then` to continue the computation.
75 //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
77 //! // Use `or_else` to handle the error.
78 //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
80 //! // Consume the result and return the contents with `unwrap`.
81 //! let final_awesome_result = good_result.ok().unwrap();
84 //! # Results must be used
86 //! A common problem with using return values to indicate errors is
87 //! that it is easy to ignore the return value, thus failing to handle
88 //! the error. Result is annotated with the #[must_use] attribute,
89 //! which will cause the compiler to issue a warning when a Result
90 //! value is ignored. This makes `Result` especially useful with
91 //! functions that may encounter errors but don't otherwise return a
94 //! Consider the `write_line` method defined for I/O types
95 //! by the [`Writer`](../io/trait.Writer.html) trait:
98 //! use std::io::IoError;
101 //! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
105 //! *Note: The actual definition of `Writer` uses `IoResult`, which
106 //! is just a synonym for `Result<T, IoError>`.*
108 //! This method doesn`t produce a value, but the write may
109 //! fail. It's crucial to handle the error case, and *not* write
110 //! something like this:
113 //! use std::io::{File, Open, Write};
115 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
116 //! // If `write_line` errors, then we'll never know, because the return
117 //! // value is ignored.
118 //! file.write_line("important message");
122 //! If you *do* write that in Rust, the compiler will by give you a
123 //! warning (by default, controlled by the `unused_must_use` lint).
125 //! You might instead, if you don't want to handle the error, simply
126 //! fail, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will fail if the write fails, proving
128 //! a marginally useful message indicating why:
131 //! use std::io::{File, Open, Write};
133 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
134 //! file.write_line("important message").ok().expect("failed to write message");
138 //! You might also simply assert success:
141 //! # use std::io::{File, Open, Write};
143 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
144 //! assert!(file.write_line("important message").is_ok());
148 //! Or propagate the error up the call stack with `try!`:
151 //! # use std::io::{File, Open, Write, IoError};
152 //! fn write_message() -> Result<(), IoError> {
153 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
154 //! try!(file.write_line("important message"));
160 //! # The `try!` macro
162 //! When writing code that calls many functions that return the
163 //! `Result` type, the error handling can be tedious. The `try!`
164 //! macro hides some of the boilerplate of propagating errors up the
167 //! It replaces this:
170 //! use std::io::{File, Open, Write, IoError};
172 //! struct Info { name: ~str, age: int, rating: int }
174 //! fn write_info(info: &Info) -> Result<(), IoError> {
175 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
176 //! // Early return on error
177 //! match file.write_line(format!("name: {}", info.name)) {
179 //! Err(e) => return Err(e)
181 //! match file.write_line(format!("age: {}", info.age)) {
183 //! Err(e) => return Err(e)
185 //! return file.write_line(format!("rating: {}", info.rating));
192 //! use std::io::{File, Open, Write, IoError};
194 //! struct Info { name: ~str, age: int, rating: int }
196 //! fn write_info(info: &Info) -> Result<(), IoError> {
197 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
198 //! // Early return on error
199 //! try!(file.write_line(format!("name: {}", info.name)));
200 //! try!(file.write_line(format!("age: {}", info.age)));
201 //! try!(file.write_line(format!("rating: {}", info.rating)));
206 //! *It's much nicer!*
208 //! Wrapping an expression in `try!` will result in the unwrapped
209 //! success (`Ok`) value, unless the result is `Err`, in which case
210 //! `Err` is returned early from the enclosing function. Its simple definition
214 //! # #![feature(macro_rules)]
215 //! macro_rules! try(
216 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
221 //! `try!` is imported by the prelude, and is available everywhere.
223 //! # `Result` and `Option`
225 //! The `Result` and [`Option`](../option/index.html) types are
226 //! similar and complementary: they are often employed to indicate a
227 //! lack of a return value; and they are trivially converted between
228 //! each other, so `Result`s are often handled by first converting to
229 //! `Option` with the [`ok`](enum.Result.html#method.ok) and
230 //! [`err`](enum.Result.html#method.ok) methods.
232 //! Whereas `Option` only indicates the lack of a value, `Result` is
233 //! specifically for error reporting, and carries with it an error
234 //! value. Sometimes `Option` is used for indicating errors, but this
235 //! is only for simple cases and is generally discouraged. Even when
236 //! there is no useful error value to return, prefer `Result<T, ()>`.
238 //! Converting to an `Option` with `ok()` to handle an error:
241 //! use std::io::Timer;
242 //! let mut t = Timer::new().ok().expect("failed to create timer!");
245 //! # `Result` vs. `fail!`
247 //! `Result` is for recoverable errors; `fail!` is for unrecoverable
248 //! errors. Callers should always be able to avoid failure if they
249 //! take the proper precautions, for example, calling `is_some()`
250 //! on an `Option` type before calling `unwrap`.
252 //! The suitability of `fail!` as an error handling mechanism is
253 //! limited by Rust's lack of any way to "catch" and resume execution
254 //! from a thrown exception. Therefore using failure for error
255 //! handling requires encapsulating fallable code in a task. Calling
256 //! the `fail!` macro, or invoking `fail!` indirectly should be
257 //! avoided as an error reporting strategy. Failure is only for
258 //! unrecoverable errors and a failing task is typically the sign of
261 //! A module that instead returns `Results` is alerting the caller
262 //! that failure is possible, and providing precise control over how
265 //! Furthermore, failure may not be recoverable at all, depending on
266 //! the context. The caller of `fail!` should assume that execution
267 //! will not resume after failure, that failure is catastrophic.
271 use iter::{Iterator, FromIterator};
272 use option::{None, Option, Some};
274 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
276 /// See the [`std::result`](index.html) module documentation for details.
277 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
279 pub enum Result<T, E> {
280 /// Contains the success value
283 /// Contains the error value
287 /////////////////////////////////////////////////////////////////////////////
288 // Type implementation
289 /////////////////////////////////////////////////////////////////////////////
291 impl<T, E> Result<T, E> {
292 /////////////////////////////////////////////////////////////////////////
293 // Querying the contained values
294 /////////////////////////////////////////////////////////////////////////
296 /// Returns true if the result is `Ok`
301 /// use std::io::{File, Open, Write};
303 /// # fn do_not_run_example() { // creates a file
304 /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
305 /// assert!(file.write_line("it's cold in here").is_ok());
309 pub fn is_ok(&self) -> bool {
316 /// Returns true if the result is `Err`
321 /// use std::io::{File, Open, Read};
323 /// // When opening with `Read` access, if the file does not exist
324 /// // then `open_mode` returns an error.
325 /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
326 /// assert!(bogus.is_err());
329 pub fn is_err(&self) -> bool {
334 /////////////////////////////////////////////////////////////////////////
335 // Adapter for each variant
336 /////////////////////////////////////////////////////////////////////////
338 /// Convert from `Result<T, E>` to `Option<T>`
340 /// Converts `self` into an `Option<T>`, consuming `self`,
341 /// and discarding the error, if any.
343 /// To convert to an `Option` without discarding the error value,
344 /// use `as_ref` to first convert the `Result<T, E>` into a
345 /// `Result<&T, &E>`.
349 /// ~~~{.should_fail}
350 /// use std::io::{File, IoResult};
352 /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
353 /// let bdays: File = bdays.ok().expect("unable to open birthday file");
356 pub fn ok(self) -> Option<T> {
363 /// Convert from `Result<T, E>` to `Option<E>`
365 /// Converts `self` into an `Option<T>`, consuming `self`,
366 /// and discarding the value, if any.
368 pub fn err(self) -> Option<E> {
375 /////////////////////////////////////////////////////////////////////////
376 // Adapter for working with references
377 /////////////////////////////////////////////////////////////////////////
379 /// Convert from `Result<T, E>` to `Result<&T, &E>`
381 /// Produces a new `Result`, containing a reference
382 /// into the original, leaving the original in place.
384 pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
387 Err(ref x) => Err(x),
391 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
393 pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
395 Ok(ref mut x) => Ok(x),
396 Err(ref mut x) => Err(x),
400 /////////////////////////////////////////////////////////////////////////
401 // Transforming contained values
402 /////////////////////////////////////////////////////////////////////////
404 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
405 /// contained `Ok` value, leaving an `Err` value untouched.
407 /// This function can be used to compose the results of two functions.
411 /// Sum the lines of a buffer by mapping strings to numbers,
412 /// ignoring I/O and parse errors:
415 /// use std::io::{BufReader, IoResult};
417 /// let buffer = "1\n2\n3\n4\n";
418 /// let mut reader = BufReader::new(buffer.as_bytes());
422 /// while !reader.eof() {
423 /// let line: IoResult<~str> = reader.read_line();
424 /// // Convert the string line to a number using `map` and `from_str`
425 /// let val: IoResult<int> = line.map(|line| {
426 /// from_str::<int>(line).unwrap_or(0)
428 /// // Add the value if there were no errors, otherwise add 0
429 /// sum += val.ok().unwrap_or(0);
433 pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
440 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
441 /// contained `Err` value, leaving an `Ok` value untouched.
443 /// This function can be used to pass through a successful result while handling
446 pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
453 ////////////////////////////////////////////////////////////////////////
454 // Boolean operations on the values, eager and lazy
455 /////////////////////////////////////////////////////////////////////////
457 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
459 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
466 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
468 /// This function can be used for control flow based on result values
470 pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
477 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
479 pub fn or(self, res: Result<T, E>) -> Result<T, E> {
486 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
488 /// This function can be used for control flow based on result values
490 pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
497 /// Unwraps a result, yielding the content of an `Ok`.
498 /// Else it returns `optb`.
500 pub fn unwrap_or(self, optb: T) -> T {
507 /// Unwraps a result, yielding the content of an `Ok`.
508 /// If the value is an `Err` then it calls `op` with its value.
510 pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
518 /////////////////////////////////////////////////////////////////////////////
520 /////////////////////////////////////////////////////////////////////////////
522 /// Takes each element in the `Iterator`: if it is an `Err`, no further
523 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
524 /// vector containing the values of each `Result` is returned.
526 /// Here is an example which increments every integer in a vector,
527 /// checking for overflow:
529 /// fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
530 /// if x == uint::MAX { return Err("overflow"); }
531 /// else { return Ok(x+1u); }
533 /// let v = [1u, 2, 3];
534 /// let res = collect(v.iter().map(|&x| inc_conditionally(x)));
535 /// assert!(res == Ok(~[2u, 3, 4]));
537 pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
538 // FIXME(#11084): This should be twice as fast once this bug is closed.
539 let mut iter = iter.scan(None, |state, x| {
549 let v: V = FromIterator::from_iter(iter.by_ref());
552 Some(err) => Err(err),
557 /// Perform a fold operation over the result values from an iterator.
559 /// If an `Err` is encountered, it is immediately returned.
560 /// Otherwise, the folded value is returned.
565 Iter: Iterator<Result<T, E>>>(
572 Ok(v) => init = f(init, v),
573 Err(u) => return Err(u)
579 /// Perform a trivial fold operation over the result values
580 /// from an iterator.
582 /// If an `Err` is encountered, it is immediately returned.
583 /// Otherwise, a simple `Ok(())` is returned.
585 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
586 fold(iterator, (), |_, _| ())
589 /////////////////////////////////////////////////////////////////////////////
591 /////////////////////////////////////////////////////////////////////////////
595 use realstd::result::{collect, fold, fold_};
596 use realstd::prelude::*;
597 use realstd::iter::range;
599 pub fn op1() -> Result<int, ~str> { Ok(666) }
600 pub fn op2() -> Result<int, ~str> { Err("sadface".to_owned()) }
604 assert_eq!(op1().and(Ok(667)).unwrap(), 667);
605 assert_eq!(op1().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "bad".to_owned());
607 assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface".to_owned());
608 assert_eq!(op2().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "sadface".to_owned());
612 pub fn test_and_then() {
613 assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
614 assert_eq!(op1().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
617 assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(),
618 "sadface".to_owned());
619 assert_eq!(op2().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
620 "sadface".to_owned());
625 assert_eq!(op1().or(Ok(667)).unwrap(), 666);
626 assert_eq!(op1().or(Err("bad".to_owned())).unwrap(), 666);
628 assert_eq!(op2().or(Ok(667)).unwrap(), 667);
629 assert_eq!(op2().or(Err("bad".to_owned())).unwrap_err(), "bad".to_owned());
633 pub fn test_or_else() {
634 assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
635 assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
637 assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
638 assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(),
639 "sadface!".to_owned());
643 pub fn test_impl_map() {
644 assert_eq!(Ok::<~str, ~str>("a".to_owned()).map(|x| x + "b"), Ok("ab".to_owned()));
645 assert_eq!(Err::<~str, ~str>("a".to_owned()).map(|x| x + "b"), Err("a".to_owned()));
649 pub fn test_impl_map_err() {
650 assert_eq!(Ok::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), Ok("a".to_owned()));
651 assert_eq!(Err::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), Err("ab".to_owned()));
656 let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
657 assert_eq!(v, Ok(vec![]));
659 let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
660 assert_eq!(v, Ok(vec![0, 1, 2]));
662 let v: Result<Vec<int>, int> = collect(range(0, 3)
663 .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
664 assert_eq!(v, Err(2));
666 // test that it does not take more elements than it needs
667 let mut functions = [|| Ok(()), || Err(1), || fail!()];
669 let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
670 assert_eq!(v, Err(1));
675 assert_eq!(fold_(range(0, 0)
676 .map(|_| Ok::<(), ()>(()))),
678 assert_eq!(fold(range(0, 3)
679 .map(|x| Ok::<int, ()>(x)),
682 assert_eq!(fold_(range(0, 3)
683 .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
686 // test that it does not take more elements than it needs
687 let mut functions = [|| Ok(()), || Err(1), || fail!()];
689 assert_eq!(fold_(functions.mut_iter()
695 pub fn test_to_str() {
696 let ok: Result<int, ~str> = Ok(100);
697 let err: Result<int, ~str> = Err("Err".to_owned());
699 assert_eq!(ok.to_str(), "Ok(100)".to_owned());
700 assert_eq!(err.to_str(), "Err(Err)".to_owned());
704 pub fn test_fmt_default() {
705 let ok: Result<int, ~str> = Ok(100);
706 let err: Result<int, ~str> = Err("Err".to_owned());
708 assert_eq!(format!("{}", ok), "Ok(100)".to_owned());
709 assert_eq!(format!("{}", err), "Err(Err)".to_owned());
713 pub fn test_unwrap_or() {
714 let ok: Result<int, ~str> = Ok(100);
715 let ok_err: Result<int, ~str> = Err("Err".to_owned());
717 assert_eq!(ok.unwrap_or(50), 100);
718 assert_eq!(ok_err.unwrap_or(50), 50);
722 pub fn test_unwrap_or_else() {
723 fn handler(msg: ~str) -> int {
724 if msg == "I got this.".to_owned() {
731 let ok: Result<int, ~str> = Ok(100);
732 let ok_err: Result<int, ~str> = Err("I got this.".to_owned());
734 assert_eq!(ok.unwrap_or_handle(handler), 100);
735 assert_eq!(ok_err.unwrap_or_handle(handler), 50);
740 pub fn test_unwrap_or_else_failure() {
741 fn handler(msg: ~str) -> int {
742 if msg == "I got this.".to_owned() {
749 let bad_err: Result<int, ~str> = Err("Unrecoverable mess.".to_owned());
750 let _ : int = bad_err.unwrap_or_handle(handler);