moduforge_rules_engine/handler/function/
error.rs

1use std::fmt::{Display, Formatter};
2
3use rquickjs::{CaughtError, Ctx, Error, Exception};
4
5pub type FunctionResult<Ok = ()> = Result<Ok, FunctionError>;
6
7#[derive(Debug)]
8pub enum FunctionError {
9    Caught(String),
10    Runtime(Error),
11}
12
13impl<'js> From<CaughtError<'js>> for FunctionError {
14    fn from(value: CaughtError<'js>) -> Self {
15        Self::Caught(value.to_string())
16    }
17}
18
19impl From<Error> for FunctionError {
20    fn from(value: Error) -> Self {
21        Self::Runtime(value)
22    }
23}
24
25impl Display for FunctionError {
26    fn fmt(
27        &self,
28        f: &mut Formatter<'_>,
29    ) -> std::fmt::Result {
30        match self {
31            FunctionError::Caught(c) => f.write_str(c.as_str()),
32            FunctionError::Runtime(rt) => rt.fmt(f),
33        }
34    }
35}
36
37pub trait ResultExt<T> {
38    #[allow(dead_code)]
39    fn or_throw_msg(
40        self,
41        ctx: &Ctx,
42        msg: &str,
43    ) -> rquickjs::Result<T>;
44    fn or_throw(
45        self,
46        ctx: &Ctx,
47    ) -> rquickjs::Result<T>;
48}
49
50impl<T, E: Display> ResultExt<T> for Result<T, E> {
51    fn or_throw_msg(
52        self,
53        ctx: &Ctx,
54        msg: &str,
55    ) -> rquickjs::Result<T> {
56        self.map_err(|_| {
57            let mut message = String::with_capacity(100);
58            message.push_str(msg);
59            message.push_str(".");
60            Exception::throw_message(ctx, &message)
61        })
62    }
63
64    fn or_throw(
65        self,
66        ctx: &Ctx,
67    ) -> rquickjs::Result<T> {
68        self.map_err(|err| Exception::throw_message(ctx, &err.to_string()))
69    }
70}
71
72impl<T> ResultExt<T> for Option<T> {
73    fn or_throw_msg(
74        self,
75        ctx: &Ctx,
76        msg: &str,
77    ) -> rquickjs::Result<T> {
78        self.ok_or(Exception::throw_message(ctx, msg))
79    }
80
81    fn or_throw(
82        self,
83        ctx: &Ctx,
84    ) -> rquickjs::Result<T> {
85        self.ok_or(Exception::throw_message(ctx, "Value is not present"))
86    }
87}