Skip to main content

rquickjs_core/
result.rs

1use core::{
2    error::Error as StdError,
3    ffi::FromBytesWithNulError,
4    fmt::{self, Display, Formatter, Result as FmtResult},
5    panic::UnwindSafe,
6    str::{FromStr, Utf8Error},
7};
8
9use alloc::{
10    ffi::{CString, NulError},
11    string::{FromUtf8Error, ToString as _},
12};
13
14#[cfg(feature = "std")]
15use std::io::Error as IoError;
16
17use crate::value::array_buffer::AsSliceError;
18use crate::{
19    atom::PredefinedAtom, qjs, runtime::UserDataError, Ctx, Exception, Object, StdResult,
20    StdString, Type, Value,
21};
22
23/// Result type used throughout the library.
24pub type Result<T> = StdResult<T, Error>;
25
26/// Result type containing an the JavaScript exception if there was one.
27pub type CaughtResult<'js, T> = StdResult<T, CaughtError<'js>>;
28
29#[derive(Debug)]
30pub enum BorrowError {
31    /// The object was not writable
32    NotWritable,
33    /// The object was already borrowed in a way that prevents borrowing again.
34    AlreadyBorrowed,
35    /// The object could only be used once and was used already.
36    AlreadyUsed,
37}
38
39impl fmt::Display for BorrowError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match *self {
42            BorrowError::NotWritable => write!(f, "tried to borrow a value which is not writable"),
43            BorrowError::AlreadyBorrowed => {
44                write!(f, "can't borrow a value as it is already borrowed")
45            }
46            BorrowError::AlreadyUsed => {
47                write!(
48                    f,
49                    "tried to use a value, which can only be used once, again."
50                )
51            }
52        }
53    }
54}
55
56impl core::error::Error for BorrowError {}
57
58/// Error type of the library.
59#[derive(Debug)]
60#[non_exhaustive]
61pub enum Error {
62    /// Could not allocate memory
63    /// This is generally only triggered when out of memory.
64    Allocation,
65    /// A module defined two exported values with the same name.
66    DuplicateExports,
67    /// Tried to export a entry which was not previously declared.
68    InvalidExport,
69    /// Tried to use or create an invalid class.
70    InvalidClass {
71        class: &'static str,
72        message: StdString,
73    },
74    /// Found a string with a internal null byte while converting
75    /// to C string.
76    InvalidString(NulError),
77    /// Found a string with a internal null byte while converting
78    /// to C string.
79    InvalidCStr(FromBytesWithNulError),
80    /// String from rquickjs was not UTF-8
81    Utf8(Utf8Error),
82    /// An io error
83    #[cfg(feature = "std")]
84    Io(IoError),
85    /// An error happened while trying to borrow a Rust class object.
86    ClassBorrow(BorrowError),
87    /// An error happened while trying to borrow a Rust function.
88    FunctionBorrow(BorrowError),
89    /// Tried to create a rust defined class with a prototype which depends on itself.
90    RecursivePrototype,
91    /// An exception raised by QuickJS itself.
92    /// The actual JavaScript value can be retrieved by calling [`Ctx::catch`].
93    ///
94    /// When returned from a callback the JavaScript will continue to unwind with the current
95    /// error.
96    Exception,
97    /// Error converting from JavaScript to a Rust type.
98    FromJs {
99        from: &'static str,
100        to: &'static str,
101        message: Option<StdString>,
102    },
103    /// Error converting to JavaScript from a Rust type.
104    IntoJs {
105        from: &'static str,
106        to: &'static str,
107        message: Option<StdString>,
108    },
109    /// Error matching of function arguments
110    MissingArgs {
111        expected: usize,
112        given: usize,
113    },
114    TooManyArgs {
115        expected: usize,
116        given: usize,
117    },
118    #[cfg(feature = "loader")]
119    /// Error when resolving js module
120    Resolving {
121        base: StdString,
122        name: StdString,
123        message: Option<StdString>,
124    },
125    #[cfg(feature = "loader")]
126    /// Error when loading js module
127    Loading {
128        name: StdString,
129        message: Option<StdString>,
130    },
131    AsSlice(AsSliceError),
132    /// Error when restoring a Persistent in a runtime other than the original runtime.
133    UnrelatedRuntime,
134    /// An error returned by a blocked on promise if block on the promise would result in a dead
135    /// lock.
136    WouldBlock,
137    /// A [`JobError`](crate::JobError)'s exception is no longer available because
138    /// a later drain released it, its runtime was dropped, or the given context
139    /// belongs to a different runtime.
140    JobErrorUnavailable,
141    /// An error related to userdata
142    UserData(UserDataError<()>),
143    /// An error from QuickJS from which the specifics are unknown.
144    /// Should eventually be removed as development progresses.
145    Unknown,
146}
147
148impl Error {
149    #[cfg(feature = "loader")]
150    /// Create resolving error
151    pub fn new_resolving<B, N>(base: B, name: N) -> Self
152    where
153        StdString: From<B> + From<N>,
154    {
155        Error::Resolving {
156            base: base.into(),
157            name: name.into(),
158            message: None,
159        }
160    }
161
162    #[cfg(feature = "loader")]
163    /// Create resolving error with message
164    pub fn new_resolving_message<B, N, M>(base: B, name: N, msg: M) -> Self
165    where
166        StdString: From<B> + From<N> + From<M>,
167    {
168        Error::Resolving {
169            base: base.into(),
170            name: name.into(),
171            message: Some(msg.into()),
172        }
173    }
174
175    #[cfg(feature = "loader")]
176    /// Returns whether the error is a resolving error
177    pub fn is_resolving(&self) -> bool {
178        matches!(self, Error::Resolving { .. })
179    }
180
181    #[cfg(feature = "loader")]
182    /// Create loading error
183    pub fn new_loading<N>(name: N) -> Self
184    where
185        StdString: From<N>,
186    {
187        Error::Loading {
188            name: name.into(),
189            message: None,
190        }
191    }
192
193    #[cfg(feature = "loader")]
194    /// Create loading error
195    pub fn new_loading_message<N, M>(name: N, msg: M) -> Self
196    where
197        StdString: From<N> + From<M>,
198    {
199        Error::Loading {
200            name: name.into(),
201            message: Some(msg.into()),
202        }
203    }
204
205    #[cfg(feature = "loader")]
206    /// Returns whether the error is a loading error
207    pub fn is_loading(&self) -> bool {
208        matches!(self, Error::Loading { .. })
209    }
210
211    /// Returns whether the error is a QuickJS generated exception.
212    pub fn is_exception(&self) -> bool {
213        matches!(self, Error::Exception)
214    }
215
216    /// Create from JS conversion error
217    pub fn new_from_js(from: &'static str, to: &'static str) -> Self {
218        Error::FromJs {
219            from,
220            to,
221            message: None,
222        }
223    }
224
225    /// Create from JS conversion error with message
226    pub fn new_from_js_message<M>(from: &'static str, to: &'static str, msg: M) -> Self
227    where
228        StdString: From<M>,
229    {
230        Error::FromJs {
231            from,
232            to,
233            message: Some(msg.into()),
234        }
235    }
236
237    /// Create into JS conversion error
238    pub fn new_into_js(from: &'static str, to: &'static str) -> Self {
239        Error::IntoJs {
240            from,
241            to,
242            message: None,
243        }
244    }
245
246    /// Create into JS conversion error with message
247    pub fn new_into_js_message<M>(from: &'static str, to: &'static str, msg: M) -> Self
248    where
249        StdString: From<M>,
250    {
251        Error::IntoJs {
252            from,
253            to,
254            message: Some(msg.into()),
255        }
256    }
257
258    /// Returns whether the error is a from JS conversion error
259    pub fn is_from_js(&self) -> bool {
260        matches!(self, Self::FromJs { .. })
261    }
262
263    /// Returns whether the error is a from JS to JS type conversion error
264    pub fn is_from_js_to_js(&self) -> bool {
265        matches!(self, Self::FromJs { to, .. } if Type::from_str(to).is_ok())
266    }
267
268    /// Returns whether the error is an into JS conversion error
269    pub fn is_into_js(&self) -> bool {
270        matches!(self, Self::IntoJs { .. })
271    }
272
273    /// Return whether the error is an function args mismatch error
274    pub fn is_num_args(&self) -> bool {
275        matches!(self, Self::TooManyArgs { .. } | Self::MissingArgs { .. })
276    }
277
278    /// Optimized conversion to [`CString`]
279    pub(crate) fn to_cstring(&self) -> CString {
280        // stringify error with NUL at end
281        let mut message = alloc::format!("{self}\0").into_bytes();
282
283        message.pop(); // pop last NUL because CString add this later
284
285        // TODO: Replace by `CString::from_vec_with_nul_unchecked` later when it will be stabilized
286        unsafe { CString::from_vec_unchecked(message) }
287    }
288
289    /// Throw an exception
290    pub(crate) fn throw(&self, ctx: &Ctx) -> qjs::JSValue {
291        use Error::*;
292        match self {
293            Exception => qjs::JS_EXCEPTION,
294            Allocation => unsafe { qjs::JS_ThrowOutOfMemory(ctx.as_ptr()) },
295            InvalidString(_)
296            | Utf8(_)
297            | FromJs { .. }
298            | IntoJs { .. }
299            | TooManyArgs { .. }
300            | MissingArgs { .. } => {
301                let message = self.to_cstring();
302                unsafe { qjs::JS_ThrowTypeError(ctx.as_ptr(), c"%s".as_ptr(), message.as_ptr()) }
303            }
304            AsSlice(_) => {
305                let message = self.to_cstring();
306                unsafe {
307                    qjs::JS_ThrowReferenceError(ctx.as_ptr(), c"%s".as_ptr(), message.as_ptr())
308                }
309            }
310            #[cfg(feature = "loader")]
311            Resolving { .. } | Loading { .. } => {
312                let message = self.to_cstring();
313                unsafe {
314                    qjs::JS_ThrowReferenceError(ctx.as_ptr(), c"%s".as_ptr(), message.as_ptr())
315                }
316            }
317            Unknown => {
318                let message = self.to_cstring();
319                unsafe {
320                    qjs::JS_ThrowInternalError(ctx.as_ptr(), c"%s".as_ptr(), message.as_ptr())
321                }
322            }
323            error => {
324                unsafe {
325                    let value = qjs::JS_NewError(ctx.as_ptr());
326                    if qjs::JS_VALUE_GET_NORM_TAG(value) == qjs::JS_TAG_EXCEPTION {
327                        //allocation error happened, can't raise error properly. just immediately
328                        //return
329                        return value;
330                    }
331                    let obj = Object::from_js_value(ctx.clone(), value);
332                    match obj.set(PredefinedAtom::Message, error.to_string()) {
333                        Ok(_) => {}
334                        Err(Error::Exception) => return qjs::JS_EXCEPTION,
335                        Err(e) => {
336                            panic!("generated error while throwing error: {}", e);
337                        }
338                    }
339                    let js_val = (obj).into_js_value();
340                    qjs::JS_Throw(ctx.as_ptr(), js_val)
341                }
342            }
343        }
344    }
345}
346
347impl StdError for Error {}
348
349impl Display for Error {
350    fn fmt(&self, f: &mut Formatter) -> FmtResult {
351        match self {
352            Error::Allocation => "Allocation failed while creating object".fmt(f)?,
353            Error::DuplicateExports => {
354                "Tried to export two values with the same name from one module".fmt(f)?
355            }
356            Error::InvalidExport => {
357                "Tried to export a value which was not previously declared".fmt(f)?
358            }
359            Error::InvalidClass { class, message } => {
360                "Invalid class '".fmt(f)?;
361                class.fmt(f)?;
362                "': ".fmt(f)?;
363                message.fmt(f)?;
364            }
365            Error::InvalidString(error) => {
366                "String contained internal null bytes: ".fmt(f)?;
367                error.fmt(f)?;
368            }
369            Error::InvalidCStr(error) => {
370                "CStr didn't end in a null byte: ".fmt(f)?;
371                error.fmt(f)?;
372            }
373            Error::Utf8(error) => {
374                "Conversion from string failed: ".fmt(f)?;
375                error.fmt(f)?;
376            }
377            Error::Unknown => "QuickJS library created a unknown error".fmt(f)?,
378            Error::Exception => "Exception generated by QuickJS".fmt(f)?,
379            Error::FromJs { from, to, message } => {
380                "Error converting from js '".fmt(f)?;
381                from.fmt(f)?;
382                "' into type '".fmt(f)?;
383                to.fmt(f)?;
384                "'".fmt(f)?;
385                if let Some(message) = message {
386                    if !message.is_empty() {
387                        ": ".fmt(f)?;
388                        message.fmt(f)?;
389                    }
390                }
391            }
392            Error::IntoJs { from, to, message } => {
393                "Error converting from '".fmt(f)?;
394                from.fmt(f)?;
395                "' into js '".fmt(f)?;
396                to.fmt(f)?;
397                "'".fmt(f)?;
398                if let Some(message) = message {
399                    if !message.is_empty() {
400                        ": ".fmt(f)?;
401                        message.fmt(f)?;
402                    }
403                }
404            }
405            Error::MissingArgs { expected, given } => {
406                "Error calling function with ".fmt(f)?;
407                given.fmt(f)?;
408                " argument(s) while ".fmt(f)?;
409                expected.fmt(f)?;
410                " where expected".fmt(f)?;
411            }
412            Error::TooManyArgs { expected, given } => {
413                "Error calling function with ".fmt(f)?;
414                given.fmt(f)?;
415                " argument(s), function is exhaustive and cannot be called with more then "
416                    .fmt(f)?;
417                expected.fmt(f)?;
418                " arguments".fmt(f)?;
419            }
420            #[cfg(feature = "loader")]
421            Error::Resolving {
422                base,
423                name,
424                message,
425            } => {
426                "Error resolving module '".fmt(f)?;
427                name.fmt(f)?;
428                "' from '".fmt(f)?;
429                base.fmt(f)?;
430                "'".fmt(f)?;
431                if let Some(message) = message {
432                    if !message.is_empty() {
433                        ": ".fmt(f)?;
434                        message.fmt(f)?;
435                    }
436                }
437            }
438            #[cfg(feature = "loader")]
439            Error::Loading { name, message } => {
440                "Error loading module '".fmt(f)?;
441                name.fmt(f)?;
442                "'".fmt(f)?;
443                if let Some(message) = message {
444                    if !message.is_empty() {
445                        ": ".fmt(f)?;
446                        message.fmt(f)?;
447                    }
448                }
449            }
450            #[cfg(feature = "std")]
451            Error::Io(error) => {
452                "IO Error: ".fmt(f)?;
453                error.fmt(f)?;
454            }
455            Error::ClassBorrow(x) => {
456                "Error borrowing class: ".fmt(f)?;
457                x.fmt(f)?;
458            }
459            Error::FunctionBorrow(x) => {
460                "Error borrowing function: ".fmt(f)?;
461                x.fmt(f)?;
462            }
463            Error::RecursivePrototype => {
464                "Error creating a class prototype depends on itself.".fmt(f)?
465            }
466            Error::WouldBlock => "Error blocking on a promise resulted in a dead lock".fmt(f)?,
467            Error::JobErrorUnavailable => {
468                "The failed job's exception is no longer available".fmt(f)?
469            }
470            Error::UserData(x) => x.fmt(f)?,
471            Error::AsSlice(x) => {
472                "Could not convert array buffer to slice: ".fmt(f)?;
473                x.fmt(f)?;
474            }
475            Error::UnrelatedRuntime => "Restoring Persistent in an unrelated runtime".fmt(f)?,
476        }
477        Ok(())
478    }
479}
480
481macro_rules! from_impls {
482    ($($type:ty => $variant:ident,)*) => {
483        $(
484            impl From<$type> for Error {
485                fn from(error: $type) -> Self {
486                    Error::$variant(error)
487                }
488            }
489        )*
490    };
491}
492
493from_impls! {
494    NulError => InvalidString,
495    FromBytesWithNulError => InvalidCStr,
496    Utf8Error => Utf8,
497}
498
499#[cfg(feature = "std")]
500from_impls! {
501    IoError => Io,
502}
503
504impl From<FromUtf8Error> for Error {
505    fn from(error: FromUtf8Error) -> Self {
506        Error::Utf8(error.utf8_error())
507    }
508}
509
510impl<T> From<UserDataError<T>> for Error {
511    fn from(_: UserDataError<T>) -> Self {
512        Error::UserData(UserDataError(()))
513    }
514}
515
516impl From<AsSliceError> for Error {
517    fn from(value: AsSliceError) -> Self {
518        Error::AsSlice(value)
519    }
520}
521
522/// An error type containing possible thrown exception values.
523#[derive(Debug)]
524pub enum CaughtError<'js> {
525    /// Error wasn't an exception
526    Error(Error),
527    /// Error was an exception and an instance of Error
528    Exception(Exception<'js>),
529    /// Error was an exception but not an instance of Error.
530    Value(Value<'js>),
531}
532
533impl<'js> Display for CaughtError<'js> {
534    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
535        match *self {
536            CaughtError::Error(ref e) => e.fmt(f),
537            CaughtError::Exception(ref e) => e.fmt(f),
538            CaughtError::Value(ref e) => {
539                writeln!(f, "Exception generated by quickjs: {e:?}")
540            }
541        }
542    }
543}
544
545impl<'js> StdError for CaughtError<'js> {}
546
547impl<'js> CaughtError<'js> {
548    /// Create a `CaughtError` from an [`Error`], retrieving the error value from `Ctx` if there
549    /// was one.
550    pub fn from_error(ctx: &Ctx<'js>, error: Error) -> Self {
551        if let Error::Exception = error {
552            let value = ctx.catch();
553            if let Some(ex) = value
554                .as_object()
555                .and_then(|x| Exception::from_object(x.clone()))
556            {
557                CaughtError::Exception(ex)
558            } else {
559                CaughtError::Value(value)
560            }
561        } else {
562            CaughtError::Error(error)
563        }
564    }
565
566    /// Turn a `Result` with [`Error`] into a result with [`CaughtError`] retrieving the error
567    /// value from the context if there was one.
568    pub fn catch<T>(ctx: &Ctx<'js>, error: Result<T>) -> CaughtResult<'js, T> {
569        error.map_err(|error| Self::from_error(ctx, error))
570    }
571
572    /// Put the possible caught value back as the current error and turn the [`CaughtError`] into [`Error`]
573    pub fn throw(self, ctx: &Ctx<'js>) -> Error {
574        match self {
575            CaughtError::Error(e) => e,
576            CaughtError::Exception(ex) => ctx.throw(ex.into_value()),
577            CaughtError::Value(ex) => ctx.throw(ex),
578        }
579    }
580
581    /// Returns whether self is of variant `CaughtError::Exception`.
582    pub fn is_exception(&self) -> bool {
583        matches!(self, CaughtError::Exception(_))
584    }
585
586    /// Returns whether self is of variant `CaughtError::Exception` or `CaughtError::Value`.
587    pub fn is_js_error(&self) -> bool {
588        matches!(self, CaughtError::Exception(_) | CaughtError::Value(_))
589    }
590}
591
592/// Extension trait to easily turn results with [`Error`] into results with [`CaughtError`]
593/// # Usage
594/// ```
595/// # use rquickjs::{Error, Context, Runtime, CaughtError};
596/// # let rt = Runtime::new().unwrap();
597/// # let ctx = Context::full(&rt).unwrap();
598/// # ctx.with(|ctx|{
599/// use rquickjs::CatchResultExt;
600///
601/// if let Err(CaughtError::Value(err)) = ctx.eval::<(),_>("throw 3").catch(&ctx){
602///     assert_eq!(err.as_int(),Some(3));
603/// # }else{
604/// #    panic!()
605/// }
606/// # });
607/// ```
608pub trait CatchResultExt<'js, T> {
609    fn catch(self, ctx: &Ctx<'js>) -> CaughtResult<'js, T>;
610}
611
612impl<'js, T> CatchResultExt<'js, T> for Result<T> {
613    fn catch(self, ctx: &Ctx<'js>) -> CaughtResult<'js, T> {
614        CaughtError::catch(ctx, self)
615    }
616}
617
618/// Extension trait to easily turn results with [`CaughtError`] into results with [`Error`]
619///
620/// Calling throw on a `CaughtError` will set the current error to the one contained in
621/// `CaughtError` if such a value exists and then turn `CaughtError` into `Error`.
622pub trait ThrowResultExt<'js, T> {
623    fn throw(self, ctx: &Ctx<'js>) -> Result<T>;
624}
625
626impl<'js, T> ThrowResultExt<'js, T> for CaughtResult<'js, T> {
627    fn throw(self, ctx: &Ctx<'js>) -> Result<T> {
628        self.map_err(|e| e.throw(ctx))
629    }
630}
631
632impl<'js> Ctx<'js> {
633    fn handle_panic_inner<R, F>(&self, f: F, err_val: R) -> R
634    where
635        F: FnOnce() -> R + UnwindSafe,
636    {
637        match crate::util::catch_unwind(f) {
638            Ok(x) => x,
639            Err(e) => unsafe {
640                self.get_runtime_opaque().set_panic(e);
641                qjs::JS_Throw(self.as_ptr(), qjs::JS_MKVAL(qjs::JS_TAG_EXCEPTION, 0));
642                err_val
643            },
644        }
645    }
646
647    pub(crate) fn handle_panic<F>(&self, f: F) -> qjs::JSValue
648    where
649        F: FnOnce() -> qjs::JSValue + UnwindSafe,
650    {
651        // JS_Throw already returns the exception tag value, so we use it directly
652        self.handle_panic_inner(f, qjs::JS_EXCEPTION)
653    }
654
655    pub(crate) fn handle_panic_exotic<F>(&self, f: F) -> qjs::c_int
656    where
657        F: FnOnce() -> qjs::c_int + UnwindSafe,
658    {
659        self.handle_panic_inner(f, -1)
660    }
661
662    /// Handle possible exceptions in [`JSValue`]'s and turn them into errors
663    /// Will return the [`JSValue`] if it is not an exception
664    ///
665    /// # Safety
666    /// Assumes to have ownership of the [`JSValue`]
667    pub(crate) unsafe fn handle_exception(&self, js_val: qjs::JSValue) -> Result<qjs::JSValue> {
668        if qjs::JS_VALUE_GET_NORM_TAG(js_val) != qjs::JS_TAG_EXCEPTION {
669            Ok(js_val)
670        } else {
671            if let Some(x) = self.get_runtime_opaque().take_panic() {
672                crate::util::resume_unwind(x);
673            }
674            Err(Error::Exception)
675        }
676    }
677
678    /// Returns [`Error::Exception`] if there is no existing panic,
679    /// otherwise continues panicking.
680    pub(crate) fn raise_exception(&self) -> Error {
681        // Safety
682        unsafe {
683            if let Some(x) = self.get_runtime_opaque().take_panic() {
684                crate::util::resume_unwind(x);
685            }
686            Error::Exception
687        }
688    }
689}