2015-02-14 11:02:45 -06:00
|
|
|
% Ergonomic error handling
|
|
|
|
|
|
|
|
Error propagation with raw `Result`s can require tedious matching and
|
|
|
|
repackaging. This tedium is largely alleviated by the `try!` macro,
|
|
|
|
and can be completely removed (in some cases) by the "`Result`-`impl`"
|
|
|
|
pattern.
|
|
|
|
|
|
|
|
### The `try!` macro
|
|
|
|
|
|
|
|
Prefer
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use std::io::{File, Open, Write, IoError};
|
|
|
|
|
|
|
|
struct Info {
|
|
|
|
name: String,
|
|
|
|
age: int,
|
|
|
|
rating: int
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_info(info: &Info) -> Result<(), IoError> {
|
|
|
|
let mut file = File::open_mode(&Path::new("my_best_friends.txt"),
|
|
|
|
Open, Write);
|
|
|
|
// Early return on error
|
2015-03-08 00:30:12 -06:00
|
|
|
try!(file.write_line(&format!("name: {}", info.name)));
|
|
|
|
try!(file.write_line(&format!("age: {}", info.age)));
|
|
|
|
try!(file.write_line(&format!("rating: {}", info.rating)));
|
2015-02-14 11:02:45 -06:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
over
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use std::io::{File, Open, Write, IoError};
|
|
|
|
|
|
|
|
struct Info {
|
|
|
|
name: String,
|
|
|
|
age: int,
|
|
|
|
rating: int
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_info(info: &Info) -> Result<(), IoError> {
|
|
|
|
let mut file = File::open_mode(&Path::new("my_best_friends.txt"),
|
|
|
|
Open, Write);
|
|
|
|
// Early return on error
|
2015-03-08 00:30:12 -06:00
|
|
|
match file.write_line(&format!("name: {}", info.name)) {
|
2015-02-14 11:02:45 -06:00
|
|
|
Ok(_) => (),
|
|
|
|
Err(e) => return Err(e)
|
|
|
|
}
|
2015-03-08 00:30:12 -06:00
|
|
|
match file.write_line(&format!("age: {}", info.age)) {
|
2015-02-14 11:02:45 -06:00
|
|
|
Ok(_) => (),
|
|
|
|
Err(e) => return Err(e)
|
|
|
|
}
|
2015-03-08 00:30:12 -06:00
|
|
|
return file.write_line(&format!("rating: {}", info.rating));
|
2015-02-14 11:02:45 -06:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
See
|
|
|
|
[the `result` module documentation](http://static.rust-lang.org/doc/master/std/result/index.html#the-try!-macro)
|
|
|
|
for more details.
|
|
|
|
|
|
|
|
### The `Result`-`impl` pattern [FIXME]
|
|
|
|
|
|
|
|
> **[FIXME]** Document the way that the `io` module uses trait impls
|
|
|
|
> on `IoResult` to painlessly propagate errors.
|