Bladeren bron

Make config load errors somewhat cleaner

We just print it out, but at least we don't get the standard rust panic
stuff.
Thomas Dy 10 jaren geleden
bovenliggende
commit
79c08680ba
2 gewijzigde bestanden met toevoegingen van 33 en 7 verwijderingen
  1. 17 5
      rust-server/src/config.rs
  2. 16 2
      rust-server/src/main.rs

+ 17 - 5
rust-server/src/config.rs

@@ -2,6 +2,7 @@ use rustc_serialize::json;
 
 use std::fs::File;
 use std::io::prelude::*;
+use std::io::Error;
 
 #[derive(RustcDecodable, Debug)]
 pub struct Config {
@@ -11,9 +12,20 @@ pub struct Config {
     pub whitelist: Vec<String>
 }
 
-pub fn load(path: &str) -> Config {
-    let mut text = String::new();
-    let mut f = File::open(path).unwrap();
-    f.read_to_string(&mut text).ok().expect("Failed to load config");
-    json::decode(&text).unwrap()
+fn stringify(err: Error) -> String {
+    format!("{}", err)
+}
+
+pub fn load(path: &str) -> Result<Config, String> {
+    File::open(path)
+        .map_err(stringify)
+        .and_then(|mut f| {
+            let mut text = String::new();
+            f.read_to_string(&mut text)
+                .map_err(stringify)
+                .map(|_| text)
+        })
+        .and_then(|text| {
+            json::decode(&text).map_err(|e| format!("{}", e))
+        })
 }

+ 16 - 2
rust-server/src/main.rs

@@ -5,11 +5,19 @@ mod config;
 mod handler;
 
 use std::env;
+use std::process;
 use hyper::Server;
 
-fn main() {
+fn actual_main() -> i32 {
     let config_path = env::args().nth(1).unwrap_or("./config.json".to_string());
-    let cfg = config::load(&config_path);
+    println!("Loading configuration from {}", config_path);
+    let cfg = match config::load(&config_path) {
+        Ok(cfg) => cfg,
+        Err(err) => {
+            println!("Failed to load configuration: {}", err);
+            return 1;
+        }
+    };
     let port = cfg.port.unwrap_or(8000);
     let site = handler::new(cfg);
 
@@ -17,4 +25,10 @@ fn main() {
     println!("Listening on {}", listen);
     Server::http(listen.as_ref() as &str).unwrap()
         .handle(site).unwrap();
+    return 0;
+}
+
+fn main() {
+    let exit_code = actual_main();
+    process::exit(exit_code);
 }