Handle bad json.

This commit is contained in:
2025-05-03 09:48:53 -04:00
parent e7c7d9f270
commit 80124af836
4 changed files with 65 additions and 7 deletions

View File

@@ -58,10 +58,18 @@ impl Document {
reply.add_data("error_type", ErrorType::DocumentAlreadyExists);
self.queue.send(reply).unwrap();
return;
},
None => {},
}
None => {}
}
let doc: Value = serde_json::from_str(&msg.get_data("doc").unwrap().to_string()).unwrap();
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();
return;
}
};
self.data
.insert(name, doc["template"].as_str().unwrap().to_string());
self.queue.send(msg.reply(MsgType::ActionOk)).unwrap();
@@ -220,7 +228,7 @@ pub mod documents {
let reply = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply.get_id(), msg.get_id());
match reply.get_msg_type() {
MsgType::Error=> {},
MsgType::Error => {}
_ => unreachable!(
"got '{:?}': should have received document",
reply.get_msg_type()
@@ -238,4 +246,30 @@ pub mod documents {
let result = binding.get_data("doc").unwrap();
assert_eq!(result.to_string(), expected.to_string());
}
#[test]
fn invalid_json() {
let (queue, rx) = setup_document();
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("action", ActionType::Add);
msg.add_data("name", "doc");
msg.add_data("doc", "Invalid json request.");
queue.send(msg.clone()).unwrap();
let reply = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply.get_id(), msg.get_id());
match reply.get_msg_type() {
MsgType::Error => {}
_ => unreachable!(
"got '{:?}': should have received document",
reply.get_msg_type()
),
}
match reply.get_data("error_type") {
Some(err) => match err.to_error_type().unwrap() {
ErrorType::DocumentInvalidRequest => {}
_ => unreachable!("got {:?}: should have been bad request'", err),
},
None => unreachable!("should contain error type"),
}
}
}