use crate::errors::errors_type::ErrorsType;
pub struct Raw {
pub data: ErrorRaw,
}
pub struct ErrorTrigger;
pub struct ErrorRaw {
pub error_type: ErrorsType,
pub message: String,
pub description: Option<String>,
pub code: Option<u64>,
pub line: Option<u64>,
pub column: Option<u64>,
pub file: Option<String>,
pub hint: Option<String>,
pub should_panic: bool,
}
impl Raw {
pub fn new(data: ErrorRaw) -> Self {
Self { data }
}
}
impl ErrorTrigger {
pub fn throw_error(error: ErrorRaw) {
let mut line_column_info = String::new();
if let Some(line) = error.line {
line_column_info.push_str(&format!("Line: {}", line));
}
if let Some(column) = error.column {
if !line_column_info.is_empty() {
line_column_info.push_str(", ");
}
line_column_info.push_str(&format!("Column: {}", column));
}
let message = if let Some(hint) = &error.hint {
format!(
"{}! [{:?}]: {}.\n\n {}\n\n Hint: {}",
get_error_type(error.error_type),
error.code,
error.message,
line_column_info,
hint,
)
} else {
format!(
"{}! [{:?}]: {}.\n\n {}",
get_error_type(error.error_type),
error.code,
error.message,
line_column_info,
)
};
if error.should_panic {
panic!("{}", message);
} else {
println!("{}", message); }
}
}
fn get_error_type(err: ErrorsType) -> &'static str {
match err {
ErrorsType::Error => "Error",
ErrorsType::Info => "Info",
ErrorsType::Warn => "Warn",
ErrorsType::Note => "Note",
ErrorsType::Debug => "Debug",
}
}
#[cfg(test)]
mod tests {
use crate::errors::errors_type::ErrorsType;
use crate::errors::raw::{ErrorRaw, ErrorTrigger, get_error_type};
#[test]
fn test_get_error_type() {
assert_eq!(get_error_type(ErrorsType::Error), "Error");
assert_eq!(get_error_type(ErrorsType::Warn), "Warn");
assert_eq!(get_error_type(ErrorsType::Note), "Note");
assert_eq!(get_error_type(ErrorsType::Debug), "Debug");
assert_eq!(get_error_type(ErrorsType::Info), "Info");
}
#[test]
fn test_throw_error_with_panic() {
let error = ErrorRaw {
error_type: ErrorsType::Error,
message: "Critical Error!".to_string(),
description: Some("A major issue occurred".to_string()),
code: Some(500),
line: Some(42),
column: Some(24),
file: None,
hint: None,
should_panic: true, };
let result = std::panic::catch_unwind(|| {
ErrorTrigger::throw_error(error);
});
assert!(result.is_err(), "Expected error, but no panic.");
}
#[test]
fn test_throw_error_without_panic() {
let error = ErrorRaw {
error_type: ErrorsType::Warn,
message: "This is just a warning!".to_string(),
description: None,
code: None,
line: Some(99),
column: None,
file: None,
hint: Some("This can be ignored.".to_string()),
should_panic: false, };
let result = std::panic::catch_unwind(|| {
ErrorTrigger::throw_error(error);
});
assert!(result.is_ok(), "No panic expected, but it happened.");
}
}