Added reply with error.

This commit is contained in:
Jeff Baskin 2025-05-03 18:14:47 -04:00
parent 80124af836
commit ce3400e353
2 changed files with 42 additions and 12 deletions

View File

@ -54,9 +54,9 @@ impl Document {
let name = msg.get_data("name").unwrap().to_string(); let name = msg.get_data("name").unwrap().to_string();
match self.data.get(&name) { match self.data.get(&name) {
Some(_) => { Some(_) => {
let mut reply = msg.reply(MsgType::Error); self.queue
reply.add_data("error_type", ErrorType::DocumentAlreadyExists); .send(msg.reply_with_error(ErrorType::DocumentAlreadyExists))
self.queue.send(reply).unwrap(); .unwrap();
return; return;
} }
None => {} None => {}
@ -64,9 +64,9 @@ impl Document {
let doc: Value = match serde_json::from_str(&msg.get_data("doc").unwrap().to_string()) { let doc: Value = match serde_json::from_str(&msg.get_data("doc").unwrap().to_string()) {
Ok(value) => value, Ok(value) => value,
Err(_) => { Err(_) => {
let mut reply = msg.reply(MsgType::Error); self.queue
reply.add_data("error_type", ErrorType::DocumentInvalidRequest); .send(msg.reply_with_error(ErrorType::DocumentInvalidRequest))
self.queue.send(reply).unwrap(); .unwrap();
return; return;
} }
}; };
@ -86,11 +86,7 @@ impl Document {
holder.add_data("doc", data.clone()); holder.add_data("doc", data.clone());
holder holder
} }
None => { None => msg.reply_with_error(ErrorType::DocumentNotFound),
let mut holder = msg.reply(MsgType::Error);
holder.add_data("error_type", ErrorType::DocumentNotFound);
holder
}
}; };
self.queue.send(reply).unwrap(); self.queue.send(reply).unwrap();
} }

View File

@ -1,4 +1,4 @@
use crate::field::Field; use crate::{field::Field, ErrorType};
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::{mpsc::Sender, Arc, RwLock}, 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 { pub fn get_msg_type(&self) -> &MsgType {
&self.msg_type &self.msg_type
} }
@ -181,6 +187,34 @@ mod messages {
msg.reset_id(); msg.reset_id();
assert_ne!(msg.get_id(), 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)] #[derive(Clone)]