#[derive(serde::Deserialize, Debug, Clone)]
pub enum ErrorCode {
NotSet = 0,
WebSocketFailedToConnect,
WebSocketErrorEncodingMessage,
WebSocketErrorDecodingMessage,
WebSocketUnknownMessageReceived,
WebSocketUnknownBinaryMessageReceived,
WebSocketError,
WebSocketClosed,
WebSocketErrorClosing,
FileNotSelected,
FileErrorReadingFile,
FileNotReady,
FileInvalidEncoding,
HexeDecodingError,
EndOfFile,
FileParsing,
RequestError,
ParsingLayerNotImplemented,
}
impl Default for ErrorCode {
fn default() -> Self {
Self::NotSet
}
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self {
Self::WebSocketFailedToConnect => "WebSocket: Failed to connect",
Self::WebSocketErrorEncodingMessage => "WebSocket: Error encoding message",
Self::WebSocketErrorDecodingMessage => "WebSocket: Error decoding message",
Self::WebSocketUnknownMessageReceived => "WebSocket: Unknown message received",
Self::WebSocketUnknownBinaryMessageReceived => "WebSocket: Unknown binary message received",
Self::WebSocketError => "WebSocket: Error",
Self::WebSocketClosed => "WebSocket: Closed",
Self::WebSocketErrorClosing => "WebSocket: Error closing",
Self::FileNotSelected => "File: No file selected",
Self::FileErrorReadingFile => "File: Error reading file",
Self::FileNotReady => "File: Not ready",
Self::FileInvalidEncoding => "File: Invalid encoding (wrong UTF-8)",
Self::NotSet => "Error code not set, please create an issue",
Self::HexeDecodingError => "Hexe decoding error",
Self::EndOfFile => "End of File",
Self::FileParsing => "File: Parsing error",
Self::RequestError => "Request error",
Self::ParsingLayerNotImplemented => "Parsing layer not implemented",
};
write!(f, "{}", str)
}
}
impl ErrorCode {
pub fn is_recoverable(&self) -> bool {
!matches!(self, Self::FileInvalidEncoding | Self::WebSocketClosed)
}
}
#[derive(serde::Deserialize, Debug, Default, Clone)]
pub struct TramexError {
pub message: String,
pub debug: String,
code: ErrorCode,
}
impl TramexError {
pub fn new(message: String, code: ErrorCode) -> Self {
log::debug!("Error: {} - {}\n{}", code, message, std::backtrace::Backtrace::capture());
Self {
message,
code,
debug: String::new(),
}
}
pub fn new_with_line(message: String, code: ErrorCode, debug: String) -> Self {
Self { message, code, debug }
}
pub fn is_recoverable(&self) -> bool {
self.code.is_recoverable()
}
pub fn get_msg(&self) -> String {
format!("[{}] {}", self.code, self.message)
}
pub fn get_code(&self) -> ErrorCode {
self.code.clone()
}
}
#[macro_export]
macro_rules! tramex_error {
($msg:expr, $code:expr) => {
TramexError::new_with_line($msg, $code, format!("{}:{}", file!(), line!()))
};
}