]> git.proxmox.com Git - rustc.git/blob - src/vendor/error-chain-0.8.1/examples/quickstart.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / vendor / error-chain-0.8.1 / examples / quickstart.rs
1 // Simple and robust error handling with error-chain!
2 // Use this as a template for new projects.
3
4 // `error_chain!` can recurse deeply
5 #![recursion_limit = "1024"]
6
7 // Import the macro. Don't forget to add `error-chain` in your
8 // `Cargo.toml`!
9 #[macro_use]
10 extern crate error_chain;
11
12 // We'll put our errors in an `errors` module, and other modules in
13 // this crate will `use errors::*;` to get access to everything
14 // `error_chain!` creates.
15 mod errors {
16 // Create the Error, ErrorKind, ResultExt, and Result types
17 error_chain! { }
18 }
19
20 use errors::*;
21
22 fn main() {
23 if let Err(ref e) = run() {
24 use ::std::io::Write;
25 let stderr = &mut ::std::io::stderr();
26 let errmsg = "Error writing to stderr";
27
28 writeln!(stderr, "error: {}", e).expect(errmsg);
29
30 for e in e.iter().skip(1) {
31 writeln!(stderr, "caused by: {}", e).expect(errmsg);
32 }
33
34 // The backtrace is not always generated. Try to run this example
35 // with `RUST_BACKTRACE=1`.
36 if let Some(backtrace) = e.backtrace() {
37 writeln!(stderr, "backtrace: {:?}", backtrace).expect(errmsg);
38 }
39
40 ::std::process::exit(1);
41 }
42 }
43
44 // Use this macro to auto-generate the main above. You may want to
45 // set the `RUST_BACKTRACE` env variable to see a backtrace.
46 //quick_main!(run);
47
48
49 // Most functions will return the `Result` type, imported from the
50 // `errors` module. It is a typedef of the standard `Result` type
51 // for which the error type is always our own `Error`.
52 fn run() -> Result<()> {
53 use std::fs::File;
54
55 // This operation will fail
56 File::open("tretrete")
57 .chain_err(|| "unable to open tretrete file")?;
58
59 Ok(())
60 }
61