add basic error handling

This commit is contained in:
Paul 2024-12-23 09:34:24 +01:00
parent 1156fa865d
commit b663cef8f0
3 changed files with 57 additions and 14 deletions

View File

@ -60,6 +60,12 @@ pub async fn apiserver() -> io::Result<()> {
pub fn handle(buf: &Vec<u8>) {
let mut rawdata = buf.to_vec();
let msg = parse_inbound_msg(&mut rawdata);
println!("{}", msg);
match parse_inbound_msg(&mut rawdata) {
Ok(o) => {
println!("msg: {}", o);
}
Err(e) => {
println!("parse inbound message error: {}", e);
}
};
}

27
src/parser/error.rs Normal file
View File

@ -0,0 +1,27 @@
pub struct MessageError;
impl std::fmt::Debug for MessageError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "invalid protocol")
}
}
impl std::fmt::Display for MessageError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "invalid protocol")
}
}
pub struct NotOurProtocolError;
impl std::fmt::Debug for NotOurProtocolError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "invalid protocol")
}
}
impl std::fmt::Display for NotOurProtocolError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "invalid protocol")
}
}

View File

@ -1,7 +1,8 @@
mod body;
mod error;
use body::*;
use std::fmt::*;
use error::*;
use bcd_convert::BcdNumber;
@ -16,13 +17,20 @@ const PROPS_RESERVED_MASK: u16 = 0xC000;
#[allow(dead_code)]
const PROPS_DATAENCRYPTION_MASK: u16 = 0x0E00;
pub fn parse_inbound_msg(rawdata: &mut Vec<u8>) -> Message {
pub fn parse_inbound_msg(rawdata: &mut Vec<u8>) -> std::result::Result<Message, MessageError> {
let mut msg: Message = Message::default();
msg.parse_header(rawdata);
match msg.parse_header(rawdata) {
Ok(_) => {
msg.check(rawdata);
}
Err(e) => {
println!("error parsing header {e}");
return Err(MessageError);
}
};
msg
Ok(msg)
}
#[derive(Default, Debug)]
@ -45,11 +53,14 @@ impl std::fmt::Display for Message {
}
impl Message {
pub fn parse_header(&mut self, rawdata: &mut Vec<u8>) {
pub fn parse_header(
&mut self,
rawdata: &mut Vec<u8>,
) -> std::result::Result<(), NotOurProtocolError> {
let mut data = rawdata.clone().into_iter();
let first_byte = data.next().unwrap();
if first_byte == FLAGDELIMITER {
println!("first flag ok");
if first_byte != FLAGDELIMITER {
return Err(NotOurProtocolError);
};
let mut tmpid = vec![];
tmpid.push(data.next().unwrap());
@ -74,12 +85,11 @@ impl Message {
self.checksum = data.next().unwrap();
if data.next().unwrap() == FLAGDELIMITER {
println!("end flag ok");
} else {
println!("error with endflag");
if data.next().unwrap() != FLAGDELIMITER {
return Err(NotOurProtocolError);
}
self.parse_body();
Ok(())
}
pub fn parse_properties(&mut self) {