use rhai::{Engine, EvalAltResult, Position}; use thiserror::Error; #[derive(Debug, Error, Clone)] pub enum SalError { #[error("File system error: {0}")] FsError(String), #[error("Download error: {0}")] DownloadError(String), #[error("Package error: {0}")] PackageError(String), #[error("{0}: {1}")] Generic(String, String), } impl SalError { pub fn new(kind: &str, message: &str) -> Self { SalError::Generic(kind.to_string(), message.to_string()) } } impl From for Box { fn from(err: SalError) -> Self { let err_msg = err.to_string(); Box::new(EvalAltResult::ErrorRuntime( err_msg.into(), Position::NONE, )) } } /// A trait for converting a Result to a Rhai-compatible error pub trait ToRhaiError { fn to_rhai_error(self) -> Result>; } impl ToRhaiError for Result { fn to_rhai_error(self) -> Result> { self.map_err(|e| { Box::new(EvalAltResult::ErrorRuntime( e.to_string().into(), Position::NONE, )) }) } } /// Register all the SalError variants with the Rhai engine /// /// # Arguments /// /// * `engine` - The Rhai engine to register the error types with /// /// # Returns /// /// * `Result<(), Box>` - Ok if registration was successful, Err otherwise pub fn register_error_types(engine: &mut Engine) -> Result<(), Box> { engine.register_type_with_name::("SalError") .register_fn("to_string", |err: &mut SalError| err.to_string()); Ok(()) }