diff --git a/src/document.rs b/src/document.rs index 31f1fe2..b9c682d 100644 --- a/src/document.rs +++ b/src/document.rs @@ -54,9 +54,9 @@ impl Document { let name = msg.get_data("name").unwrap().to_string(); match self.data.get(&name) { Some(_) => { - let mut reply = msg.reply(MsgType::Error); - reply.add_data("error_type", ErrorType::DocumentAlreadyExists); - self.queue.send(reply).unwrap(); + self.queue + .send(msg.reply_with_error(ErrorType::DocumentAlreadyExists)) + .unwrap(); return; } None => {} @@ -64,9 +64,9 @@ impl Document { let doc: Value = match serde_json::from_str(&msg.get_data("doc").unwrap().to_string()) { Ok(value) => value, Err(_) => { - let mut reply = msg.reply(MsgType::Error); - reply.add_data("error_type", ErrorType::DocumentInvalidRequest); - self.queue.send(reply).unwrap(); + self.queue + .send(msg.reply_with_error(ErrorType::DocumentInvalidRequest)) + .unwrap(); return; } }; @@ -86,11 +86,7 @@ impl Document { holder.add_data("doc", data.clone()); holder } - None => { - let mut holder = msg.reply(MsgType::Error); - holder.add_data("error_type", ErrorType::DocumentNotFound); - holder - } + None => msg.reply_with_error(ErrorType::DocumentNotFound), }; self.queue.send(reply).unwrap(); } diff --git a/src/queue.rs b/src/queue.rs index b3f6bcc..2387131 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -1,4 +1,4 @@ -use crate::field::Field; +use crate::{field::Field, ErrorType}; use std::{ collections::HashMap, sync::{mpsc::Sender, Arc, RwLock}, @@ -48,6 +48,12 @@ impl Message { } } + pub fn reply_with_error(&self, error: ErrorType) -> Self { + let mut reply = self.reply(MsgType::Error); + reply.add_data("error_type", error); + reply + } + pub fn get_msg_type(&self) -> &MsgType { &self.msg_type } @@ -181,6 +187,34 @@ mod messages { msg.reset_id(); assert_ne!(msg.get_id(), id); } + + #[test] + fn error_reply() { + let msg = Message::new(MsgType::Time); + let errors = [ + ErrorType::DocumentAlreadyExists, + ErrorType::DocumentInvalidRequest, + ]; + for error in errors.into_iter() { + let reply = msg.reply_with_error(error.clone()); + assert_eq!(reply.get_id(), msg.get_id()); + assert_eq!( + format!("{:?}", reply.get_msg_type()), + format!("{:?}", MsgType::Error) + ); + assert_eq!( + format!( + "{:?}", + reply + .get_data("error_type") + .unwrap() + .to_error_type() + .unwrap() + ), + format!("{:?}", error) + ); + } + } } #[derive(Clone)]