diff --git a/src/lib.rs b/src/lib.rs index 4dbd814..1c3377e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,7 +10,7 @@ use std::{ pub struct Malestorm<'a> { node: RefCell, io: MalestormIo, - pub handlers: HashMap<&'a str, Box)>>, + pub handlers: HashMap<&'a str, Box) -> Result<(), String>>>, } struct Node { @@ -96,7 +96,9 @@ impl<'a> Malestorm<'a> { } }; - handler(message, pc); + if let Err(e) = handler(message, pc) { + eprintln!("error in serving request: {}", e); + } } } @@ -113,7 +115,7 @@ impl<'a> Malestorm<'a> { pub fn register( &mut self, name: &'a str, - func: impl Fn(Message, Rc) + 'a + 'static, + func: impl Fn(Message, Rc) -> Result<(), String> + 'a + 'static, ) { self.handlers.insert(name, Box::new(func)); } diff --git a/src/main.rs b/src/main.rs index 8da0f75..58a748b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,37 +7,38 @@ use std::rc::Rc; fn main() { let mut program = Malestorm::default(); - program.register("init", |mut msg: Message, program: Rc| { - let message_body: InitMessage = serde_json::from_value(msg.body.message_body.take()) - .expect("error in parsing message body"); + program.register( + "init", + // TODO: Replace error string with a type + |mut msg: Message, program: Rc| -> Result<(), String> { + let message_body: InitMessage = serde_json::from_value(msg.body.message_body.take()) + .map_err(|e| format!("error in parsing response body: {}", e))?; - program.set_node_id(message_body.node_id); - program.set_nodes(message_body.nodes); + program.set_node_id(message_body.node_id); + program.set_nodes(message_body.nodes); - msg.body.message_type = "init_ok".into(); + msg.body.message_type = "init_ok".into(); - match program.reply(msg) { - Ok(_) => (), - Err(e) => { - eprintln!("init: error in writing response: {}", e); - } - } - }); + program + .reply(msg) + .map_err(|e| format!("init: error in writing response: {}", e)) + }, + ); - program.register("echo", |mut msg: Message, program: Rc| { - let message_body: EchoMessage = serde_json::from_value(msg.body.message_body.take()) - .expect("error in parsing message body"); + program.register( + "echo", + |mut msg: Message, program: Rc| -> Result<(), String> { + let message_body: EchoMessage = serde_json::from_value(msg.body.message_body.take()) + .map_err(|e| format!("error in parsing response body: {}", e))?; - msg.body.message_type = "echo_ok".into(); - msg.body.message_body = serde_json::to_value(message_body).unwrap(); + msg.body.message_type = "echo_ok".into(); + msg.body.message_body = serde_json::to_value(message_body).unwrap(); - match program.reply(msg) { - Ok(_) => (), - Err(e) => { - eprintln!("echo: error in writing response: {}", e); - } - } - }); + program + .reply(msg) + .map_err(|e| format!("echo: error in writing response: {}", e)) + }, + ); program.run(); }