rust-s7-datatypes/src/errors.rs

56 lines
1.4 KiB
Rust
Raw Normal View History

2021-10-22 15:59:36 +00:00
use std::fmt;
use std::error::Error;
use anyhow::{anyhow};
2021-10-16 15:17:09 +00:00
2021-10-22 15:59:36 +00:00
#[derive(Debug)]
pub enum Errors {
MissingBit,
InvalidBit,
MissingLength,
InvalidLength,
UnknownType,
ConversionError{
byte: u32,
type_string: String,
}
}
impl Errors {
fn conversion(&self) -> &str {
match self {
Self::MissingBit => "Missing bit position.",
Self::InvalidBit => "Invalid value for bit. Expecting u8 between 0 and 7.",
Self::MissingLength => "Missing data length.",
Self::InvalidLength => "Invalid value for data_length in DBItem. Expecting u32.",
Self::UnknownType => "Unknown datatype",
Self::ConversionError{byte: _, type_string: _} => "Cannot convert data into type.",
}
}
}
impl fmt::Display for Errors {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let err_msg = self.conversion();
write!(f, "{}", err_msg)
}
}
impl Error for Errors {
fn description(&self) -> &str {
self.conversion()
}
}
pub fn serial_error(name: String, pos: u32) -> anyhow::Error {
2021-10-16 15:17:09 +00:00
anyhow!(
"Cannot convert Serial data for type '{}' at position {}.",
name,
pos
)
}
2021-10-22 15:59:36 +00:00
pub fn s7_read_error(name: String, pos: u32) -> anyhow::Error {
2021-10-16 15:17:09 +00:00
anyhow!("Cannot read Byte for type '{}' at position {}.", name, pos)
}