Skip to main content

nsh_js/
error.rs

1use rquickjs::{CaughtError, Ctx};
2
3/// A JS exception or engine error, rendered to a message with stack.
4#[derive(Debug, Clone, thiserror::Error)]
5#[error("{message}")]
6pub struct JsError {
7    /// Message, including the JS stack when available.
8    pub message: String,
9    /// The exception was `null`: what QuickJS leaves when it could not
10    /// even make its "out of memory" error.
11    pub(crate) null: bool,
12}
13
14impl JsError {
15    pub(crate) fn caught(err: CaughtError<'_>) -> Self {
16        let null = matches!(&err, CaughtError::Value(v) if v.is_null());
17        Self {
18            message: err.to_string(),
19            null,
20        }
21    }
22
23    /// An error with `message`.
24    pub(crate) fn new(message: String) -> Self {
25        Self {
26            message,
27            null: false,
28        }
29    }
30
31    pub(crate) fn from_engine(cx: &Ctx<'_>, err: rquickjs::Error) -> Self {
32        Self::caught(CaughtError::from_error(cx, err))
33    }
34}
35
36impl From<rquickjs::Error> for JsError {
37    fn from(err: rquickjs::Error) -> Self {
38        Self::new(err.to_string())
39    }
40}