-
-
Notifications
You must be signed in to change notification settings - Fork 610
Expand file tree
/
Copy patherror.rs
More file actions
1535 lines (1429 loc) · 51.5 KB
/
error.rs
File metadata and controls
1535 lines (1429 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Error-related types and conversions.
use crate::{
builtins::{error::Error, Array},
js_string,
object::JsObject,
property::PropertyDescriptor,
realm::Realm,
Context, JsString, JsValue,
};
use boa_gc::{custom_trace, Finalize, Trace};
use std::{borrow::Cow, error, fmt};
use thiserror::Error;
/// Create an error object from a value or string literal. Optionally the
/// first argument of the macro can be a type of error (such as `TypeError`,
/// `RangeError` or `InternalError`).
///
/// Can be used with an expression that converts into `JsValue` or a format
/// string with arguments.
///
/// # Native Errors
///
/// The only native error that is not buildable using this macro is
/// `AggregateError`, which requires multiple error objects available at
/// construction.
///
/// [`InternalError`][mdn] is non-standard and unsupported in Boa.
///
/// All other native error types can be created from the macro using their
/// JavaScript name followed by a colon, like:
///
/// ```ignore
/// js_error!(TypeError: "hello world");
/// ```
///
/// # Examples
///
/// ```
/// # use boa_engine::{js_str, Context, JsValue};
/// use boa_engine::{js_error};
/// let context = &mut Context::default();
///
/// let error = js_error!("error!");
/// assert!(error.as_opaque().is_some());
/// assert_eq!(error.as_opaque().unwrap().to_string(context).unwrap(), "error!");
///
/// let error = js_error!("error: {}", 5);
/// assert_eq!(error.as_opaque().unwrap().to_string(context).unwrap(), "error: 5");
///
/// // Non-string literals must be used as an expression.
/// let error = js_error!({ true });
/// assert_eq!(error.as_opaque().unwrap(), &JsValue::from(true));
/// ```
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError
#[macro_export]
macro_rules! js_error {
(Error: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::ERROR.with_message($value)
)
};
(Error: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::ERROR
.with_message(format!($value $(, $args)*))
)
};
(TypeError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::TYP.with_message($value)
)
};
(TypeError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::TYP
.with_message(format!($value $(, $args)*))
)
};
(SyntaxError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::SYNTAX.with_message($value)
)
};
(SyntaxError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::SYNTAX.with_message(format!($value $(, $args)*))
)
};
(RangeError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::RANGE.with_message($value)
)
};
(RangeError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::RANGE.with_message(format!($value $(, $args)*))
)
};
(EvalError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::EVAL.with_message($value)
)
};
(EvalError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::EVAL.with_message(format!($value $(, $args)*))
)
};
(ReferenceError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::REFERENCE.with_message($value)
)
};
(ReferenceError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::REFERENCE.with_message(format!($value $(, $args)*))
)
};
(URIError: $value: literal) => {
$crate::JsError::from_native(
$crate::JsNativeError::URI.with_message($value)
)
};
(URIError: $value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_native(
$crate::JsNativeError::URI.with_message(format!($value $(, $args)*))
)
};
($value: literal) => {
$crate::JsError::from_opaque($crate::JsValue::from(
$crate::js_string!($value)
))
};
($value: expr) => {
$crate::JsError::from_opaque(
$crate::JsValue::from($value)
)
};
($value: literal $(, $args: expr)* $(,)?) => {
$crate::JsError::from_opaque($crate::JsValue::from(
$crate::JsString::from(format!($value $(, $args)*))
))
};
}
/// The error type returned by all operations related
/// to the execution of Javascript code.
///
/// This is essentially an enum that can store either [`JsNativeError`]s (for ideal
/// native errors) or opaque [`JsValue`]s, since Javascript allows throwing any valid
/// `JsValue`.
///
/// The implementation doesn't provide a [`From`] conversion
/// for `JsValue`. This is with the intent of encouraging the usage of proper
/// `JsNativeError`s instead of plain `JsValue`s. However, if you
/// do need a proper opaque error, you can construct one using the
/// [`JsError::from_opaque`] method.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsError, JsNativeError, JsNativeErrorKind, JsValue, js_string};
/// let cause = JsError::from_opaque(js_string!("error!").into());
///
/// assert!(cause.as_opaque().is_some());
/// assert_eq!(
/// cause.as_opaque().unwrap(),
/// &JsValue::from(js_string!("error!"))
/// );
///
/// let native_error: JsError = JsNativeError::typ()
/// .with_message("invalid type!")
/// .with_cause(cause)
/// .into();
///
/// assert!(native_error.as_native().is_some());
///
/// let kind = &native_error.as_native().unwrap().kind;
/// assert!(matches!(kind, JsNativeErrorKind::Type));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Trace, Finalize)]
#[boa_gc(unsafe_no_drop)]
pub struct JsError {
inner: Repr,
}
/// Internal representation of a [`JsError`].
///
/// `JsError` is represented by an opaque enum because it restricts
/// matching against `JsError` without calling `try_native` first.
/// This allows us to provide a safe API for `Error` objects that extracts
/// their info as a native `Rust` type ([`JsNativeError`]).
///
/// This should never be used outside of this module. If that's not the case,
/// you should add methods to either `JsError` or `JsNativeError` to
/// represent that special use case.
#[derive(Debug, Clone, PartialEq, Eq, Trace, Finalize)]
#[boa_gc(unsafe_no_drop)]
enum Repr {
Native(JsNativeError),
Opaque(JsValue),
}
/// The error type returned by the [`JsError::try_native`] method.
#[derive(Debug, Clone, Error)]
pub enum TryNativeError {
/// A property of the error object has an invalid type.
#[error("invalid type of property `{0}`")]
InvalidPropertyType(&'static str),
/// The message of the error object could not be decoded.
#[error("property `message` cannot contain unpaired surrogates")]
InvalidMessageEncoding,
/// The constructor property of the error object was invalid.
#[error("invalid `constructor` property of Error object")]
InvalidConstructor,
/// A property of the error object is not accessible.
#[error("could not access property `{property}`")]
InaccessibleProperty {
/// The name of the property that could not be accessed.
property: &'static str,
/// The source error.
source: JsError,
},
/// An inner error of an aggregate error is not accessible.
#[error("could not get element `{index}` of property `errors`")]
InvalidErrorsIndex {
/// The index of the error that could not be accessed.
index: u64,
/// The source error.
source: JsError,
},
/// The error value is not an error object.
#[error("opaque error of type `{:?}` is not an Error object", .0.get_type())]
NotAnErrorObject(JsValue),
/// The original realm of the error object was inaccessible.
#[error("could not access realm of Error object")]
InaccessibleRealm {
/// The source error.
source: JsError,
},
}
impl error::Error for JsError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.inner {
Repr::Native(err) => err.source(),
Repr::Opaque(_) => None,
}
}
}
impl JsError {
/// Creates a new `JsError` from a native error `err`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsError, JsNativeError};
/// let error = JsError::from_native(JsNativeError::syntax());
///
/// assert!(error.as_native().is_some());
/// ```
#[must_use]
pub const fn from_native(err: JsNativeError) -> Self {
Self {
inner: Repr::Native(err),
}
}
/// Creates a new `JsError` from a Rust standard error `err`.
/// This will create a new `JsNativeError` with the message of the standard error.
///
/// # Examples
///
/// ```
/// # use boa_engine::JsError;
/// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!");
/// let js_error: JsError = JsError::from_rust(error);
///
/// assert_eq!(js_error.as_native().unwrap().message(), "oh no!");
/// assert!(js_error.as_native().unwrap().cause().is_none());
/// ```
#[must_use]
pub fn from_rust(err: impl error::Error) -> Self {
let mut native_err = JsNativeError::error().with_message(err.to_string());
if let Some(source) = err.source() {
native_err = native_err.with_cause(Self::from_rust(source));
}
Self::from_native(native_err)
}
/// Creates a new `JsError` from an opaque error `value`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::JsError;
/// let error = JsError::from_opaque(5.0f64.into());
///
/// assert!(error.as_opaque().is_some());
/// ```
#[must_use]
pub const fn from_opaque(value: JsValue) -> Self {
Self {
inner: Repr::Opaque(value),
}
}
/// Converts the error to an opaque `JsValue` error
///
/// Unwraps the inner `JsValue` if the error is already an opaque error.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{Context, JsError, JsNativeError};
/// # use boa_engine::builtins::error::Error;
/// let context = &mut Context::default();
/// let error: JsError = JsNativeError::eval().with_message("invalid script").into();
/// let error_val = error.to_opaque(context);
///
/// assert!(error_val.as_object().unwrap().is::<Error>());
/// ```
pub fn to_opaque(&self, context: &mut Context) -> JsValue {
match &self.inner {
Repr::Native(e) => e.to_opaque(context).into(),
Repr::Opaque(v) => v.clone(),
}
}
/// Unwraps the inner error if this contains a native error.
/// Otherwise, inspects the opaque error and tries to extract the
/// necessary information to construct a native error similar to the provided
/// opaque error. If the conversion fails, returns a [`TryNativeError`]
/// with the cause of the failure.
///
/// # Note 1
///
/// This method won't try to make any conversions between JS types.
/// In other words, for this conversion to succeed:
/// - `message` **MUST** be a `JsString` value.
/// - `errors` (in the case of `AggregateError`s) **MUST** be an `Array` object.
///
/// # Note 2
///
/// This operation should be considered a lossy conversion, since it
/// won't store any additional properties of the opaque
/// error, other than `message`, `cause` and `errors` (in the case of
/// `AggregateError`s). If you cannot affort a lossy conversion, clone
/// the object before calling [`from_opaque`][JsError::from_opaque]
/// to preserve its original properties.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{Context, JsError, JsNativeError, JsNativeErrorKind};
/// let context = &mut Context::default();
///
/// // create a new, opaque Error object
/// let error: JsError = JsNativeError::typ().with_message("type error!").into();
/// let error_val = error.to_opaque(context);
///
/// // then, try to recover the original
/// let error = JsError::from_opaque(error_val).try_native(context).unwrap();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Type));
/// assert_eq!(error.message(), "type error!");
/// ```
pub fn try_native(&self, context: &mut Context) -> Result<JsNativeError, TryNativeError> {
match &self.inner {
Repr::Native(e) => Ok(e.clone()),
Repr::Opaque(val) => {
let obj = val
.as_object()
.ok_or_else(|| TryNativeError::NotAnErrorObject(val.clone()))?;
let error = *obj
.downcast_ref::<Error>()
.ok_or_else(|| TryNativeError::NotAnErrorObject(val.clone()))?;
let try_get_property = |key: JsString, name, context: &mut Context| {
obj.try_get(key, context)
.map_err(|e| TryNativeError::InaccessibleProperty {
property: name,
source: e,
})
};
let message = if let Some(msg) =
try_get_property(js_string!("message"), "message", context)?
{
Cow::Owned(
msg.as_string()
.map(JsString::to_std_string)
.transpose()
.map_err(|_| TryNativeError::InvalidMessageEncoding)?
.ok_or(TryNativeError::InvalidPropertyType("message"))?,
)
} else {
Cow::Borrowed("")
};
let cause = try_get_property(js_string!("cause"), "cause", context)?;
let kind = match error {
Error::Error => JsNativeErrorKind::Error,
Error::Eval => JsNativeErrorKind::Eval,
Error::Type => JsNativeErrorKind::Type,
Error::Range => JsNativeErrorKind::Range,
Error::Reference => JsNativeErrorKind::Reference,
Error::Syntax => JsNativeErrorKind::Syntax,
Error::Uri => JsNativeErrorKind::Uri,
Error::Aggregate => {
let errors = obj.get(js_string!("errors"), context).map_err(|e| {
TryNativeError::InaccessibleProperty {
property: "errors",
source: e,
}
})?;
let mut error_list = Vec::new();
match errors.as_object() {
Some(errors) if errors.is_array() => {
let length = errors.length_of_array_like(context).map_err(|e| {
TryNativeError::InaccessibleProperty {
property: "errors.length",
source: e,
}
})?;
for i in 0..length {
error_list.push(Self::from_opaque(
errors.get(i, context).map_err(|e| {
TryNativeError::InvalidErrorsIndex {
index: i,
source: e,
}
})?,
));
}
}
_ => return Err(TryNativeError::InvalidPropertyType("errors")),
}
JsNativeErrorKind::Aggregate(error_list)
}
};
let realm = try_get_property(js_string!("constructor"), "constructor", context)?
.as_ref()
.and_then(JsValue::as_constructor)
.ok_or(TryNativeError::InvalidConstructor)?
.get_function_realm(context)
.map_err(|err| TryNativeError::InaccessibleRealm { source: err })?;
Ok(JsNativeError {
kind,
message,
cause: cause.map(|v| Box::new(Self::from_opaque(v))),
realm: Some(realm),
})
}
}
}
/// Gets the inner [`JsValue`] if the error is an opaque error,
/// or `None` otherwise.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsError, JsNativeError};
/// let error: JsError = JsNativeError::reference()
/// .with_message("variable not found!")
/// .into();
///
/// assert!(error.as_opaque().is_none());
///
/// let error = JsError::from_opaque(256u32.into());
///
/// assert!(error.as_opaque().is_some());
/// ```
#[must_use]
pub const fn as_opaque(&self) -> Option<&JsValue> {
match self.inner {
Repr::Native(_) => None,
Repr::Opaque(ref v) => Some(v),
}
}
/// Gets the inner [`JsNativeError`] if the error is a native
/// error, or `None` otherwise.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsError, JsNativeError, JsValue};
/// let error: JsError = JsNativeError::error().with_message("Unknown error").into();
///
/// assert!(error.as_native().is_some());
///
/// let error = JsError::from_opaque(JsValue::undefined());
///
/// assert!(error.as_native().is_none());
/// ```
#[must_use]
pub const fn as_native(&self) -> Option<&JsNativeError> {
match &self.inner {
Repr::Native(e) => Some(e),
Repr::Opaque(_) => None,
}
}
/// Converts this error into its thread-safe, erased version.
///
/// Even though this operation is lossy, converting into a `JsErasedError`
/// is useful since it implements `Send` and `Sync`, making it compatible with
/// error reporting frameworks such as `anyhow`, `eyre` or `miette`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{js_string, Context, JsError, JsNativeError, JsSymbol, JsValue};
/// # use std::error::Error;
/// let context = &mut Context::default();
/// let cause = JsError::from_opaque(JsSymbol::new(Some(js_string!("error!"))).unwrap().into());
///
/// let native_error: JsError = JsNativeError::typ()
/// .with_message("invalid type!")
/// .with_cause(cause)
/// .into();
///
/// let erased_error = native_error.into_erased(context);
///
/// assert_eq!(erased_error.to_string(), "TypeError: invalid type!");
///
/// let send_sync_error: Box<dyn Error + Send + Sync> = Box::new(erased_error);
///
/// assert_eq!(
/// send_sync_error.source().unwrap().to_string(),
/// "Symbol(error!)"
/// );
/// ```
pub fn into_erased(self, context: &mut Context) -> JsErasedError {
let Ok(native) = self.try_native(context) else {
return JsErasedError {
inner: ErasedRepr::Opaque(Cow::Owned(self.to_string())),
};
};
let JsNativeError {
kind,
message,
cause,
..
} = native;
let cause = cause.map(|err| Box::new(err.into_erased(context)));
let kind = match kind {
JsNativeErrorKind::Aggregate(errors) => JsErasedNativeErrorKind::Aggregate(
errors
.into_iter()
.map(|err| err.into_erased(context))
.collect(),
),
JsNativeErrorKind::Error => JsErasedNativeErrorKind::Error,
JsNativeErrorKind::Eval => JsErasedNativeErrorKind::Eval,
JsNativeErrorKind::Range => JsErasedNativeErrorKind::Range,
JsNativeErrorKind::Reference => JsErasedNativeErrorKind::Reference,
JsNativeErrorKind::Syntax => JsErasedNativeErrorKind::Syntax,
JsNativeErrorKind::Type => JsErasedNativeErrorKind::Type,
JsNativeErrorKind::Uri => JsErasedNativeErrorKind::Uri,
JsNativeErrorKind::RuntimeLimit => JsErasedNativeErrorKind::RuntimeLimit,
#[cfg(feature = "fuzz")]
JsNativeErrorKind::NoInstructionsRemain => unreachable!(
"The NoInstructionsRemain native error cannot be converted to an erased kind."
),
};
JsErasedError {
inner: ErasedRepr::Native(JsErasedNativeError {
kind,
message,
cause,
}),
}
}
/// Injects a realm on the `realm` field of a native error.
///
/// This is a no-op if the error is not native or if the `realm` field of the error is already
/// set.
pub(crate) fn inject_realm(mut self, realm: Realm) -> Self {
match &mut self.inner {
Repr::Native(err) if err.realm.is_none() => {
err.realm = Some(realm);
}
_ => {}
}
self
}
/// Is the [`JsError`] catchable in JavaScript.
#[inline]
pub(crate) fn is_catchable(&self) -> bool {
self.as_native().is_none_or(JsNativeError::is_catchable)
}
}
impl From<boa_parser::Error> for JsError {
fn from(err: boa_parser::Error) -> Self {
Self::from(JsNativeError::from(err))
}
}
impl From<JsNativeError> for JsError {
fn from(error: JsNativeError) -> Self {
Self {
inner: Repr::Native(error),
}
}
}
impl fmt::Display for JsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.inner {
Repr::Native(e) => e.fmt(f),
Repr::Opaque(v) => v.display().fmt(f),
}
}
}
/// Native representation of an ideal `Error` object from Javascript.
///
/// This representation is more space efficient than its [`JsObject`] equivalent,
/// since it doesn't need to create a whole new `JsObject` to be instantiated.
/// Prefer using this over [`JsError`] when you don't need to throw
/// plain [`JsValue`]s as errors, or when you need to inspect the error type
/// of a `JsError`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let native_error = JsNativeError::uri().with_message("cannot decode uri");
///
/// match native_error.kind {
/// JsNativeErrorKind::Uri => { /* handle URI error*/ }
/// _ => unreachable!(),
/// }
///
/// assert_eq!(native_error.message(), "cannot decode uri");
/// ```
#[derive(Clone, Finalize, Error, PartialEq, Eq)]
pub struct JsNativeError {
/// The kind of native error (e.g. `TypeError`, `SyntaxError`, etc.)
pub kind: JsNativeErrorKind,
message: Cow<'static, str>,
#[source]
cause: Option<Box<JsError>>,
realm: Option<Realm>,
}
impl fmt::Display for JsNativeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)?;
let message = self.message.trim();
if !message.is_empty() {
write!(f, ": {message}")?;
}
Ok(())
}
}
// SAFETY: just mirroring the default derive to allow destructuring.
unsafe impl Trace for JsNativeError {
custom_trace!(this, mark, {
mark(&this.kind);
mark(&this.cause);
mark(&this.realm);
});
}
impl fmt::Debug for JsNativeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JsNativeError")
.field("kind", &self.kind)
.field("message", &self.message)
.field("cause", &self.cause)
.finish_non_exhaustive()
}
}
impl JsNativeError {
/// Default `AggregateError` kind `JsNativeError`.
pub const AGGREGATE: Self = Self::aggregate(Vec::new());
/// Default `Error` kind `JsNativeError`.
pub const ERROR: Self = Self::error();
/// Default `EvalError` kind `JsNativeError`.
pub const EVAL: Self = Self::eval();
/// Default `RangeError` kind `JsNativeError`.
pub const RANGE: Self = Self::range();
/// Default `ReferenceError` kind `JsNativeError`.
pub const REFERENCE: Self = Self::reference();
/// Default `SyntaxError` kind `JsNativeError`.
pub const SYNTAX: Self = Self::syntax();
/// Default `error` kind `JsNativeError`.
pub const TYP: Self = Self::typ();
/// Default `UriError` kind `JsNativeError`.
pub const URI: Self = Self::uri();
#[cfg(feature = "fuzz")]
/// Default `NoInstructionsRemain` kind `JsNativeError`.
pub const NO_INSTRUCTIONS_REMAIN: Self = Self::no_instructions_remain();
/// Default `error` kind `JsNativeError`.
pub const RUNTIME_LIMIT: Self = Self::runtime_limit();
/// Creates a new `JsNativeError` from its `kind`, `message` and (optionally) its `cause`.
const fn new(
kind: JsNativeErrorKind,
message: Cow<'static, str>,
cause: Option<Box<JsError>>,
) -> Self {
Self {
kind,
message,
cause,
realm: None,
}
}
/// Creates a new `JsNativeError` of kind `AggregateError` from a list of [`JsError`]s, with
/// empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let inner_errors = vec![
/// JsNativeError::typ().into(),
/// JsNativeError::syntax().into()
/// ];
/// let error = JsNativeError::aggregate(inner_errors);
///
/// assert!(matches!(
/// error.kind,
/// JsNativeErrorKind::Aggregate(ref errors) if errors.len() == 2
/// ));
/// ```
#[must_use]
#[inline]
pub const fn aggregate(errors: Vec<JsError>) -> Self {
Self::new(
JsNativeErrorKind::Aggregate(errors),
Cow::Borrowed(""),
None,
)
}
/// Check if it's a [`JsNativeErrorKind::Aggregate`].
#[must_use]
#[inline]
pub const fn is_aggregate(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Aggregate(_))
}
/// Creates a new `JsNativeError` of kind `Error`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::error();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Error));
/// ```
#[must_use]
#[inline]
pub const fn error() -> Self {
Self::new(JsNativeErrorKind::Error, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Error`].
#[must_use]
#[inline]
pub const fn is_error(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Error)
}
/// Creates a new `JsNativeError` of kind `EvalError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::eval();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Eval));
/// ```
#[must_use]
#[inline]
pub const fn eval() -> Self {
Self::new(JsNativeErrorKind::Eval, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Eval`].
#[must_use]
#[inline]
pub const fn is_eval(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Eval)
}
/// Creates a new `JsNativeError` of kind `RangeError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::range();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Range));
/// ```
#[must_use]
#[inline]
pub const fn range() -> Self {
Self::new(JsNativeErrorKind::Range, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Range`].
#[must_use]
#[inline]
pub const fn is_range(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Range)
}
/// Creates a new `JsNativeError` of kind `ReferenceError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::reference();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Reference));
/// ```
#[must_use]
#[inline]
pub const fn reference() -> Self {
Self::new(JsNativeErrorKind::Reference, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Reference`].
#[must_use]
#[inline]
pub const fn is_reference(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Reference)
}
/// Creates a new `JsNativeError` of kind `SyntaxError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::syntax();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Syntax));
/// ```
#[must_use]
#[inline]
pub const fn syntax() -> Self {
Self::new(JsNativeErrorKind::Syntax, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Syntax`].
#[must_use]
#[inline]
pub const fn is_syntax(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Syntax)
}
/// Creates a new `JsNativeError` of kind `TypeError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::typ();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Type));
/// ```
#[must_use]
#[inline]
pub const fn typ() -> Self {
Self::new(JsNativeErrorKind::Type, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Type`].
#[must_use]
#[inline]
pub const fn is_type(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Type)
}
/// Creates a new `JsNativeError` of kind `UriError`, with empty `message` and undefined `cause`.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::{JsNativeError, JsNativeErrorKind};
/// let error = JsNativeError::uri();
///
/// assert!(matches!(error.kind, JsNativeErrorKind::Uri));
/// ```
#[must_use]
#[inline]
pub const fn uri() -> Self {
Self::new(JsNativeErrorKind::Uri, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::Uri`].
#[must_use]
#[inline]
pub const fn is_uri(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::Uri)
}
/// Creates a new `JsNativeError` that indicates that the context hit its execution limit. This
/// is only used in a fuzzing context.
#[cfg(feature = "fuzz")]
#[must_use]
pub const fn no_instructions_remain() -> Self {
Self::new(
JsNativeErrorKind::NoInstructionsRemain,
Cow::Borrowed(""),
None,
)
}
/// Check if it's a [`JsNativeErrorKind::NoInstructionsRemain`].
#[must_use]
#[inline]
#[cfg(feature = "fuzz")]
pub const fn is_no_instructions_remain(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::NoInstructionsRemain)
}
/// Creates a new `JsNativeError` that indicates that the context exceeded the runtime limits.
#[must_use]
#[inline]
pub const fn runtime_limit() -> Self {
Self::new(JsNativeErrorKind::RuntimeLimit, Cow::Borrowed(""), None)
}
/// Check if it's a [`JsNativeErrorKind::RuntimeLimit`].
#[must_use]
#[inline]
pub const fn is_runtime_limit(&self) -> bool {
matches!(self.kind, JsNativeErrorKind::RuntimeLimit)
}
/// Sets the message of this error.
///
/// # Examples
///
/// ```rust
/// # use boa_engine::JsNativeError;
/// let error = JsNativeError::range().with_message("number too large");
///
/// assert_eq!(error.message(), "number too large");
/// ```
#[must_use]
#[inline]
pub fn with_message<S>(mut self, message: S) -> Self
where
S: Into<Cow<'static, str>>,
{
self.message = message.into();
self
}
/// Sets the cause of this error.
///