Skip to main content

sal_rhai/
error.rs

1use rhai::{Engine, EvalAltResult, Position};
2use thiserror::Error;
3
4#[derive(Debug, Error, Clone)]
5pub enum SalError {
6    #[error("File system error: {0}")]
7    FsError(String),
8    #[error("Download error: {0}")]
9    DownloadError(String),
10    #[error("Package error: {0}")]
11    PackageError(String),
12    #[error("{0}: {1}")]
13    Generic(String, String),
14}
15
16impl SalError {
17    pub fn new(kind: &str, message: &str) -> Self {
18        SalError::Generic(kind.to_string(), message.to_string())
19    }
20}
21
22impl From<SalError> for Box<EvalAltResult> {
23    fn from(err: SalError) -> Self {
24        let err_msg = err.to_string();
25        Box::new(EvalAltResult::ErrorRuntime(err_msg.into(), Position::NONE))
26    }
27}
28
29/// A trait for converting a Result to a Rhai-compatible error
30pub trait ToRhaiError<T> {
31    fn to_rhai_error(self) -> Result<T, Box<EvalAltResult>>;
32}
33
34impl<T, E: std::error::Error> ToRhaiError<T> for Result<T, E> {
35    fn to_rhai_error(self) -> Result<T, Box<EvalAltResult>> {
36        self.map_err(|e| {
37            Box::new(EvalAltResult::ErrorRuntime(
38                e.to_string().into(),
39                Position::NONE,
40            ))
41        })
42    }
43}
44
45/// Register all the SalError variants with the Rhai engine
46///
47/// # Arguments
48///
49/// * `engine` - The Rhai engine to register the error types with
50///
51/// # Returns
52///
53/// * `Result<(), Box<EvalAltResult>>` - Ok if registration was successful, Err otherwise
54pub fn register_error_types(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
55    engine
56        .register_type_with_name::<SalError>("SalError")
57        .register_fn("to_string", |err: &mut SalError| err.to_string());
58    Ok(())
59}