| 1 |
//! Demonstrates usage of `Error::caused` method. This method enables chaining errors |
| 2 |
//! like `ResultExt::chain_err` but doesn't require the presence of a `Result` wrapper. |
| 3 |
|
| 4 |
#[macro_use] |
| 5 |
extern crate error_chain; |
| 6 |
|
| 7 |
use std::fs::File; |
| 8 |
|
| 9 |
mod errors { |
| 10 |
use super::LaunchStage; |
| 11 |
use std::io; |
| 12 |
|
| 13 |
error_chain! { |
| 14 |
foreign_links { |
| 15 |
Io(io::Error) #[doc = "Error during IO"]; |
| 16 |
} |
| 17 |
|
| 18 |
errors { |
| 19 |
Launch(phase: LaunchStage) { |
| 20 |
description("An error occurred during startup") |
| 21 |
display("Startup aborted: {:?} did not complete successfully", phase) |
| 22 |
} |
| 23 |
|
| 24 |
ConfigLoad(path: String) { |
| 25 |
description("Config file not found") |
| 26 |
display("Unable to read file `{}`", path) |
| 27 |
} |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
impl From<LaunchStage> for ErrorKind { |
| 32 |
fn from(v: LaunchStage) -> Self { |
| 33 |
ErrorKind::Launch(v) |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
pub use errors::*; |
| 39 |
|
| 40 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 41 |
pub enum LaunchStage { |
| 42 |
ConfigLoad, |
| 43 |
ConfigParse, |
| 44 |
ConfigResolve, |
| 45 |
} |
| 46 |
|
| 47 |
/// Read the service config from the file specified. |
| 48 |
fn load_config(rel_path: &str) -> Result<()> { |
| 49 |
File::open(rel_path) |
| 50 |
.map(|_| ()) |
| 51 |
.chain_err(|| ErrorKind::ConfigLoad(rel_path.to_string())) |
| 52 |
} |
| 53 |
|
| 54 |
/// Launch the service. |
| 55 |
fn launch(rel_path: &str) -> Result<()> { |
| 56 |
load_config(rel_path).map_err(|e| match e { |
| 57 |
e @ Error(ErrorKind::ConfigLoad(_), _) => e.chain_err(|| LaunchStage::ConfigLoad), |
| 58 |
e => e.chain_err(|| "Unknown failure"), |
| 59 |
}) |
| 60 |
} |
| 61 |
|
| 62 |
fn main() { |
| 63 |
let chain = launch("does_not_exist.json").unwrap_err(); |
| 64 |
for err in chain.iter() { |
| 65 |
println!("{}", err); |
| 66 |
} |
| 67 |
} |