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
23pub type Result<T> = StdResult<T, Error>;
25
26pub type CaughtResult<'js, T> = StdResult<T, CaughtError<'js>>;
28
29#[derive(Debug)]
30pub enum BorrowError {
31 NotWritable,
33 AlreadyBorrowed,
35 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#[derive(Debug)]
60#[non_exhaustive]
61pub enum Error {
62 Allocation,
65 DuplicateExports,
67 InvalidExport,
69 InvalidClass {
71 class: &'static str,
72 message: StdString,
73 },
74 InvalidString(NulError),
77 InvalidCStr(FromBytesWithNulError),
80 Utf8(Utf8Error),
82 #[cfg(feature = "std")]
84 Io(IoError),
85 ClassBorrow(BorrowError),
87 FunctionBorrow(BorrowError),
89 RecursivePrototype,
91 Exception,
97 FromJs {
99 from: &'static str,
100 to: &'static str,
101 message: Option<StdString>,
102 },
103 IntoJs {
105 from: &'static str,
106 to: &'static str,
107 message: Option<StdString>,
108 },
109 MissingArgs {
111 expected: usize,
112 given: usize,
113 },
114 TooManyArgs {
115 expected: usize,
116 given: usize,
117 },
118 #[cfg(feature = "loader")]
119 Resolving {
121 base: StdString,
122 name: StdString,
123 message: Option<StdString>,
124 },
125 #[cfg(feature = "loader")]
126 Loading {
128 name: StdString,
129 message: Option<StdString>,
130 },
131 AsSlice(AsSliceError),
132 UnrelatedRuntime,
134 WouldBlock,
137 JobErrorUnavailable,
141 UserData(UserDataError<()>),
143 Unknown,
146}
147
148impl Error {
149 #[cfg(feature = "loader")]
150 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 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 pub fn is_resolving(&self) -> bool {
178 matches!(self, Error::Resolving { .. })
179 }
180
181 #[cfg(feature = "loader")]
182 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 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 pub fn is_loading(&self) -> bool {
208 matches!(self, Error::Loading { .. })
209 }
210
211 pub fn is_exception(&self) -> bool {
213 matches!(self, Error::Exception)
214 }
215
216 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 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 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 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 pub fn is_from_js(&self) -> bool {
260 matches!(self, Self::FromJs { .. })
261 }
262
263 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 pub fn is_into_js(&self) -> bool {
270 matches!(self, Self::IntoJs { .. })
271 }
272
273 pub fn is_num_args(&self) -> bool {
275 matches!(self, Self::TooManyArgs { .. } | Self::MissingArgs { .. })
276 }
277
278 pub(crate) fn to_cstring(&self) -> CString {
280 let mut message = alloc::format!("{self}\0").into_bytes();
282
283 message.pop(); unsafe { CString::from_vec_unchecked(message) }
287 }
288
289 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 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#[derive(Debug)]
524pub enum CaughtError<'js> {
525 Error(Error),
527 Exception(Exception<'js>),
529 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 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 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 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 pub fn is_exception(&self) -> bool {
583 matches!(self, CaughtError::Exception(_))
584 }
585
586 pub fn is_js_error(&self) -> bool {
588 matches!(self, CaughtError::Exception(_) | CaughtError::Value(_))
589 }
590}
591
592pub 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
618pub 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 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 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 pub(crate) fn raise_exception(&self) -> Error {
681 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}