Skip to main content

rquickjs_core/value/
exception.rs

1use alloc::string::String;
2use core::mem::{self, MaybeUninit};
3use core::{error::Error as ErrorTrait, fmt};
4
5use crate::{atom::PredefinedAtom, convert::Coerced, qjs, Ctx, Error, Object, Result, Value};
6
7/// A JavaScript instance of Error
8///
9/// Will turn into a error when converted to JavaScript but won't automatically be thrown.
10#[repr(transparent)]
11#[derive(Clone, Eq, PartialEq, Hash)]
12pub struct Exception<'js>(pub(crate) Object<'js>);
13
14impl<'js> ErrorTrait for Exception<'js> {}
15
16impl fmt::Debug for Exception<'_> {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.debug_struct("Exception")
19            .field("message", &self.message())
20            .field("stack", &self.stack())
21            .finish()
22    }
23}
24
25/// Writes as many characters of `str` as will fit into `buf`, followed by a nul byte.
26///
27/// QuickJS implementation doesn't allow error strings longer than 256 anyway so
28/// truncating here is fine.
29fn truncate_cstr_into(buf: &mut [MaybeUninit<u8>; 256], mut str: &str) {
30    let mut max = buf.len() - 1;
31    if str.len() > max {
32        // while the byte at len is a continue byte shorten the byte.
33        // TODO: use floor_char_boundary when MSRV is at least 1.91
34        while (str.as_bytes()[max] & 0b1100_0000) == 0b1000_0000 {
35            max -= 1;
36        }
37        str = &str[..max];
38    }
39    unsafe {
40        // SAFETY: these slice types have the same layout
41        buf[..str.len()]
42            .copy_from_slice(mem::transmute::<&[u8], &[MaybeUninit<u8>]>(str.as_bytes()));
43    }
44    buf[str.len()].write(0u8);
45}
46
47impl<'js> Exception<'js> {
48    /// Turns the exception into the underlying object.
49    pub fn into_object(self) -> Object<'js> {
50        self.0
51    }
52
53    /// Returns a reference to the underlying object.
54    pub fn as_object(&self) -> &Object<'js> {
55        &self.0
56    }
57
58    /// Creates an exception from an object if it is an instance of error.
59    pub fn from_object(obj: Object<'js>) -> Option<Self> {
60        if obj.is_error() {
61            Some(Self(obj))
62        } else {
63            None
64        }
65    }
66
67    /// Creates a new exception with a given message.
68    pub fn from_message(ctx: Ctx<'js>, message: &str) -> Result<Self> {
69        let obj = unsafe {
70            let value = ctx.handle_exception(qjs::JS_NewError(ctx.as_ptr()))?;
71            Value::from_js_value(ctx, value)
72                .into_object()
73                .expect("`JS_NewError` did not return an object")
74        };
75        obj.set(PredefinedAtom::Message, message)?;
76        Ok(Exception(obj))
77    }
78
79    /// Returns the message of the error.
80    ///
81    /// Same as retrieving `error.message` in JavaScript.
82    pub fn message(&self) -> Option<String> {
83        self.get::<_, Option<Coerced<String>>>(PredefinedAtom::Message)
84            .ok()
85            .and_then(|x| x)
86            .map(|x| x.0)
87    }
88
89    /// Returns the error stack.
90    ///
91    /// Same as retrieving `error.stack` in JavaScript.
92    pub fn stack(&self) -> Option<String> {
93        self.get::<_, Option<Coerced<String>>>(PredefinedAtom::Stack)
94            .ok()
95            .and_then(|x| x)
96            .map(|x| x.0)
97    }
98
99    /// Throws a new generic error.
100    ///
101    /// Equivalent to:
102    /// ```rust
103    /// # use rquickjs::{Runtime,Context,Exception};
104    /// # let rt = Runtime::new().unwrap();
105    /// # let ctx = Context::full(&rt).unwrap();
106    /// # ctx.with(|ctx|{
107    /// # let _ = {
108    /// # let message = "";
109    /// let (Ok(e) | Err(e)) = Exception::from_message(ctx, message).map(|x| x.throw());
110    /// e
111    /// # };
112    /// # })
113    /// ```
114    pub fn throw_message(ctx: &Ctx<'js>, message: &str) -> Error {
115        let (Ok(e) | Err(e)) = Self::from_message(ctx.clone(), message).map(|x| x.throw());
116        e
117    }
118
119    /// Throws a new syntax error.
120    pub fn throw_syntax(ctx: &Ctx<'js>, message: &str) -> Error {
121        let mut buffer = [MaybeUninit::uninit(); 256];
122        truncate_cstr_into(&mut buffer, message);
123        unsafe {
124            let res = qjs::JS_ThrowSyntaxError(ctx.as_ptr(), c"%s".as_ptr(), buffer.as_mut_ptr());
125            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
126        }
127        Error::Exception
128    }
129
130    /// Throws a new type error.
131    pub fn throw_type(ctx: &Ctx<'js>, message: &str) -> Error {
132        let mut buffer = [MaybeUninit::uninit(); 256];
133        truncate_cstr_into(&mut buffer, message);
134        unsafe {
135            let res = qjs::JS_ThrowTypeError(ctx.as_ptr(), c"%s".as_ptr(), buffer.as_mut_ptr());
136            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
137        }
138        Error::Exception
139    }
140
141    /// Throws a new reference error.
142    pub fn throw_reference(ctx: &Ctx<'js>, message: &str) -> Error {
143        let mut buffer = [MaybeUninit::uninit(); 256];
144        truncate_cstr_into(&mut buffer, message);
145        unsafe {
146            let res =
147                qjs::JS_ThrowReferenceError(ctx.as_ptr(), c"%s".as_ptr(), buffer.as_mut_ptr());
148            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
149        }
150        Error::Exception
151    }
152
153    /// Throws a new range error.
154    pub fn throw_range(ctx: &Ctx<'js>, message: &str) -> Error {
155        let mut buffer = [MaybeUninit::uninit(); 256];
156        truncate_cstr_into(&mut buffer, message);
157        unsafe {
158            let res = qjs::JS_ThrowRangeError(ctx.as_ptr(), c"%s".as_ptr(), buffer.as_mut_ptr());
159            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
160        }
161        Error::Exception
162    }
163
164    /// Throws a new internal error.
165    pub fn throw_internal(ctx: &Ctx<'js>, message: &str) -> Error {
166        let mut buffer = [MaybeUninit::uninit(); 256];
167        truncate_cstr_into(&mut buffer, message);
168        unsafe {
169            let res = qjs::JS_ThrowInternalError(ctx.as_ptr(), c"%s".as_ptr(), buffer.as_mut_ptr());
170            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
171        }
172        Error::Exception
173    }
174
175    /// Throws a new DOMException.
176    pub fn throw_dom(ctx: &Ctx<'js>, name: &str, message: &str) -> Error {
177        let mut name_buffer = [MaybeUninit::uninit(); 256];
178        truncate_cstr_into(&mut name_buffer, name);
179        let mut message_buffer = [MaybeUninit::uninit(); 256];
180        truncate_cstr_into(&mut message_buffer, message);
181        unsafe {
182            let res = qjs::JS_ThrowDOMException(
183                ctx.as_ptr(),
184                name_buffer.as_ptr().cast(),
185                c"%s".as_ptr(),
186                message_buffer.as_mut_ptr(),
187            );
188            debug_assert_eq!(qjs::JS_VALUE_GET_NORM_TAG(res), qjs::JS_TAG_EXCEPTION);
189        }
190        Error::Exception
191    }
192
193    /// Sets the exception as the current error and returns `Error::Exception`
194    pub fn throw(self) -> Error {
195        let ctx = self.ctx().clone();
196        ctx.throw(self.0.into_value())
197    }
198}
199
200impl fmt::Display for Exception<'_> {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        "Error:".fmt(f)?;
203        if let Some(message) = self.message() {
204            ' '.fmt(f)?;
205            message.fmt(f)?;
206        }
207        if let Some(stack) = self.stack() {
208            '\n'.fmt(f)?;
209            stack.fmt(f)?;
210        }
211        Ok(())
212    }
213}
214
215#[cfg(test)]
216mod test {
217    use crate::{
218        atom::PredefinedAtom, context::intrinsic, Context, Error, Exception, Object, Runtime,
219    };
220
221    #[test]
222    fn test_throw_dom() {
223        let rt = Runtime::new().unwrap();
224        let ctx = Context::custom::<intrinsic::DOMException>(&rt).unwrap();
225        ctx.with(|ctx| {
226            let e = Exception::throw_dom(&ctx, "SyntaxError", "oh no");
227            assert!(matches!(e, Error::Exception), "{e}");
228            let exception = ctx.catch().into_object().unwrap();
229            assert!(exception.is_instance_of(
230                ctx.globals()
231                    .get::<_, Object>(PredefinedAtom::DOMException)
232                    .unwrap()
233            ));
234            assert_eq!(
235                exception.get::<_, i32>("code").unwrap(),
236                // SyntaxError's legacy code
237                12
238            );
239        });
240    }
241}