-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy patherror.rs
More file actions
2400 lines (2205 loc) · 76.3 KB
/
error.rs
File metadata and controls
2400 lines (2205 loc) · 76.3 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
// Copyright 2018-2026 the Deno authors. MIT license.
use std::borrow::Cow;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Write as _;
use std::sync::Arc;
use boxed_error::Boxed;
use deno_error::JsError;
use deno_error::JsErrorClass;
use deno_error::PropertyValue;
use deno_error::builtin_classes::*;
use thiserror::Error;
pub use super::modules::ModuleConcreteError;
use crate::FastStaticString;
pub use crate::io::ResourceError;
pub use crate::modules::ModuleLoaderError;
use crate::runtime::JsRealm;
use crate::runtime::JsRuntime;
use crate::runtime::v8_static_strings;
use crate::source_map::SourceMapApplication;
use crate::url::Url;
/// A generic wrapper that can encapsulate any concrete error type.
// TODO(ry) Deprecate AnyError and encourage deno_core::anyhow::Error instead.
pub type AnyError = anyhow::Error;
deno_error::js_error_wrapper!(v8::DataError, DataError, TYPE_ERROR);
impl PartialEq<DataError> for DataError {
fn eq(&self, other: &DataError) -> bool {
match (self.0, other.0) {
(
v8::DataError::BadType { actual, expected },
v8::DataError::BadType {
actual: other_actual,
expected: other_expected,
},
) => actual == other_actual && expected == other_expected,
(
v8::DataError::NoData { expected },
v8::DataError::NoData {
expected: other_expected,
},
) => expected == other_expected,
_ => false,
}
}
}
impl Eq for DataError {}
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error("Failed to parse {0}")]
pub struct CoreModuleParseError(pub FastStaticString);
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error("Failed to execute {0}")]
pub struct CoreModuleExecuteError(pub FastStaticString);
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error("Unable to get code cache from unbound module script for {0}")]
pub struct CreateCodeCacheError(pub Url);
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error(
"Extensions from snapshot loaded in wrong order: expected {} but got {}", .expected, .actual
)]
pub struct ExtensionSnapshotMismatchError {
pub expected: &'static str,
pub actual: &'static str,
}
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error(
"Number of lazy-initialized extensions ({}) does not match number of arguments ({})", .lazy_init_extensions_len, .arguments_len
)]
pub struct ExtensionLazyInitCountMismatchError {
pub lazy_init_extensions_len: usize,
pub arguments_len: usize,
}
#[derive(Debug, Error, JsError)]
#[class(generic)]
#[error(
"Lazy-initialized extensions loaded in wrong order: expected {} but got {}", .expected, .actual
)]
pub struct ExtensionLazyInitOrderMismatchError {
pub expected: &'static str,
pub actual: &'static str,
}
#[derive(Debug, Boxed, JsError)]
pub struct CoreError(pub Box<CoreErrorKind>);
#[derive(Debug, thiserror::Error, JsError)]
pub enum CoreErrorKind {
#[class(generic)]
#[error("Top-level await is not allowed in synchronous evaluation")]
TLA,
#[class(inherit)]
#[error(transparent)]
Js(#[from] Box<JsError>),
#[class(inherit)]
#[error(transparent)]
Io(#[from] std::io::Error),
#[class(inherit)]
#[error(transparent)]
ExtensionTranspiler(deno_error::JsErrorBox),
#[class(inherit)]
#[error(transparent)]
Parse(#[from] CoreModuleParseError),
#[class(inherit)]
#[error(transparent)]
Execute(#[from] CoreModuleExecuteError),
#[class(generic)]
#[error(
"Following modules were passed to ExtModuleLoader but never used:\n{}",
.0.iter().map(|s| format!(" - {}\n", s)).collect::<Vec<_>>().join("")
)]
UnusedModules(Vec<String>),
#[class(generic)]
#[error(
"Following modules were not evaluated; make sure they are imported from other code:\n{}",
.0.iter().map(|s| format!(" - {}\n", s)).collect::<Vec<_>>().join("")
)]
NonEvaluatedModules(Vec<String>),
#[class(generic)]
#[error("{0} not present in the module map")]
MissingFromModuleMap(String),
#[class(generic)]
#[error("Could not execute {specifier}")]
CouldNotExecute {
#[source]
error: Box<Self>,
specifier: String,
},
#[class(inherit)]
#[error(transparent)]
JsBox(#[from] deno_error::JsErrorBox),
#[class(inherit)]
#[error(transparent)]
Url(#[from] url::ParseError),
#[class(generic)]
#[error(
"Cannot evaluate module, because JavaScript execution has been terminated"
)]
ExecutionTerminated,
#[class(generic)]
#[error(
"Promise resolution is still pending but the event loop has already resolved"
)]
PendingPromiseResolution,
#[class(generic)]
#[error(
"Cannot evaluate dynamically imported module, because JavaScript execution has been terminated"
)]
EvaluateDynamicImportedModule,
#[class(inherit)]
#[error(transparent)]
Module(ModuleConcreteError),
#[class(inherit)]
#[error(transparent)]
Data(DataError),
#[class(inherit)]
#[error(transparent)]
CreateCodeCache(#[from] CreateCodeCacheError),
#[class(inherit)]
#[error(transparent)]
ExtensionSnapshotMismatch(ExtensionSnapshotMismatchError),
#[class(inherit)]
#[error(transparent)]
ExtensionLazyInitCountMismatch(ExtensionLazyInitCountMismatchError),
#[class(inherit)]
#[error(transparent)]
ExtensionLazyInitOrderMismatch(ExtensionLazyInitOrderMismatchError),
}
impl CoreError {
pub fn print_with_cause(&self) -> String {
use std::error::Error;
let mut err_message = self.to_string();
if let Some(source) = self.source() {
err_message.push_str(&format!(
"\n\nCaused by:\n {}",
source.to_string().replace("\n", "\n ")
));
}
err_message
}
pub fn to_v8_error(&self, scope: &mut v8::PinScope) -> v8::Global<v8::Value> {
self.as_kind().to_v8_error(scope)
}
}
impl CoreErrorKind {
pub fn to_v8_error(&self, scope: &mut v8::PinScope) -> v8::Global<v8::Value> {
let err_string = self.get_message().to_string();
let mut error_chain = vec![];
let mut intermediary_error: Option<&dyn Error> = Some(&self);
while let Some(err) = intermediary_error {
if let Some(source) = err.source() {
let source_str = source.to_string();
if source_str != err_string {
error_chain.push(source_str);
}
intermediary_error = Some(source);
} else {
intermediary_error = None;
}
}
let message = if !error_chain.is_empty() {
format!(
"{}\n Caused by:\n {}",
err_string,
error_chain.join("\n ")
)
} else {
err_string
};
let exception =
js_class_and_message_to_exception(scope, &self.get_class(), &message);
v8::Global::new(scope, exception)
}
}
impl From<v8::DataError> for CoreError {
fn from(err: v8::DataError) -> Self {
CoreErrorKind::Data(DataError(err)).into_box()
}
}
pub fn throw_js_error_class(
scope: &mut v8::PinScope,
error: &dyn JsErrorClass,
) {
let exception = js_class_and_message_to_exception(
scope,
&error.get_class(),
&error.get_message(),
);
scope.throw_exception(exception);
}
fn js_class_and_message_to_exception<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
_class: &str,
message: &str,
) -> v8::Local<'s, v8::Value> {
let message = v8::String::new(scope, message).unwrap();
/*
commented out since this was previously only handling type errors, but this
change is breaking CLI, so visiting on a later date
match class {
TYPE_ERROR => v8::Exception::type_error(scope, message),
RANGE_ERROR => v8::Exception::range_error(scope, message),
REFERENCE_ERROR => v8::Exception::reference_error(scope, message),
SYNTAX_ERROR => v8::Exception::syntax_error(scope, message),
_ => v8::Exception::error(scope, message),
}*/
v8::Exception::type_error(scope, message)
}
pub fn to_v8_error<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
error: &dyn JsErrorClass,
) -> v8::Local<'s, v8::Value> {
v8::tc_scope!(let tc_scope, scope);
let cb = JsRealm::exception_state_from_scope(tc_scope)
.js_build_custom_error_cb
.borrow()
.clone()
.expect("Custom error builder must be set");
let cb = cb.open(tc_scope);
let this = v8::undefined(tc_scope).into();
let class = v8::String::new(tc_scope, &error.get_class()).unwrap();
let message = v8::String::new(tc_scope, &error.get_message()).unwrap();
let mut args = vec![class.into(), message.into()];
let additional_properties = error
.get_additional_properties()
.map(|(key, value)| {
let key = v8::String::new(tc_scope, &key).unwrap().into();
let value = match value {
PropertyValue::String(value) => {
v8::String::new(tc_scope, &value).unwrap().into()
}
PropertyValue::Number(value) => v8::Number::new(tc_scope, value).into(),
};
v8::Array::new_with_elements(tc_scope, &[key, value]).into()
})
.collect::<Vec<_>>();
if !additional_properties.is_empty() {
args.push(
v8::Array::new_with_elements(tc_scope, &additional_properties).into(),
);
}
let maybe_exception = cb.call(tc_scope, this, &args);
match maybe_exception {
Some(exception) => exception,
None => {
let mut msg =
"Custom error class must have a builder registered".to_string();
if tc_scope.has_caught() {
let e = tc_scope.exception().unwrap();
// If the builder threw a bare `null`/`undefined`, propagate the
// original message instead of panicking on an opaque "Uncaught null".
if e.is_null_or_undefined() {
return message.into();
}
let js_error = JsError::from_v8_exception(tc_scope, e);
msg = format!("{}: {}", msg, js_error.exception_message);
}
panic!("{}", msg);
}
}
}
/// Effectively throw an uncatchable error. This will terminate runtime
/// execution before any more JS code can run, except in the REPL where it
/// should just output the error to the console.
pub fn dispatch_exception<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
exception: v8::Local<'s, v8::Value>,
promise: bool,
) {
let state = JsRuntime::state_from(scope);
if let Some(true) = state.with_inspector(|inspector| {
inspector.exception_thrown(scope, exception, false);
inspector.is_dispatching_message()
}) {
// This indicates that the fn is being called from a REPL. Skip termination.
return;
}
JsRealm::exception_state_from_scope(scope)
.set_dispatched_exception(v8::Global::new(scope, exception), promise);
scope.terminate_execution();
}
#[inline(always)]
pub(crate) fn call_site_evals_key<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
) -> v8::Local<'s, v8::Private> {
let name = v8_static_strings::CALL_SITE_EVALS.v8_string(scope).unwrap();
v8::Private::for_api(scope, Some(name))
}
/// A `JsError` represents an exception coming from V8, with stack frames and
/// line numbers. The deno_cli crate defines another `JsError` type, which wraps
/// the one defined here, that adds source map support and colorful formatting.
/// When updating this struct, also update errors_are_equal_without_cause() in
/// fmt_error.rs.
#[derive(Debug, PartialEq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JsError {
pub name: Option<String>,
pub message: Option<String>,
pub stack: Option<String>,
pub cause: Option<Box<JsError>>,
pub exception_message: String,
pub frames: Vec<JsStackFrame>,
pub source_line: Option<String>,
pub source_line_frame_index: Option<usize>,
pub aggregated: Option<Vec<JsError>>,
pub additional_properties: Vec<(String, String)>,
}
impl JsErrorClass for JsError {
fn get_class(&self) -> Cow<'static, str> {
if let Some(name) = &self.name {
Cow::Owned(name.clone())
} else {
Cow::Borrowed(GENERIC_ERROR)
}
}
fn get_message(&self) -> Cow<'static, str> {
if let Some(message) = &self.message {
Cow::Owned(message.clone())
} else {
Cow::Borrowed("")
}
}
fn get_additional_properties(&self) -> deno_error::AdditionalProperties {
Box::new(
self
.additional_properties
// todo(dsherret): why does JsErrorClass not allow having references within this struct?
.clone()
.into_iter()
.map(|(k, v)| {
(
Cow::Owned(k.to_string()),
PropertyValue::String(Cow::Owned(v.to_string())),
)
}),
)
}
fn get_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self
}
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JsStackFrame {
pub type_name: Option<String>,
pub function_name: Option<String>,
pub method_name: Option<String>,
pub file_name: Option<String>,
pub line_number: Option<i64>,
pub column_number: Option<i64>,
pub eval_origin: Option<String>,
// Warning! isToplevel has inconsistent snake<>camel case, "typo" originates in v8:
// https://source.chromium.org/search?q=isToplevel&sq=&ss=chromium%2Fchromium%2Fsrc:v8%2F
#[serde(rename = "isToplevel")]
pub is_top_level: Option<bool>,
pub is_eval: bool,
pub is_native: bool,
pub is_constructor: bool,
pub is_async: bool,
pub is_promise_all: bool,
pub is_wasm: bool,
pub promise_index: Option<i64>,
}
/// Applies source map to the given location
fn apply_source_map<'a>(
source_mapper: &mut crate::source_map::SourceMapper,
file_name: Cow<'a, str>,
line_number: i64,
column_number: i64,
) -> (Cow<'a, str>, i64, i64) {
match source_mapper.apply_source_map(
&file_name,
line_number as u32,
column_number as u32,
) {
SourceMapApplication::Unchanged => (file_name, line_number, column_number),
SourceMapApplication::LineAndColumn {
line_number,
column_number,
} => (file_name, line_number.into(), column_number.into()),
SourceMapApplication::LineAndColumnAndFileName {
file_name,
line_number,
column_number,
} => (file_name.into(), line_number.into(), column_number.into()),
}
}
/// Parses an eval origin string from V8, returning
/// the contents before the location,
/// (the file name, line number, and column number), and
/// the contents after the location.
///
/// # Example
/// ```ignore
/// assert_eq!(
/// parse_eval_origin("eval at foo (bar at (file://a.ts:1:2))"),
/// Some(("eval at foo (bar at (", ("file://a.ts", 1, 2), "))")),
/// );
/// ```
///
fn parse_eval_origin(
eval_origin: &str,
) -> Option<(&str, (&str, i64, i64), &str)> {
// The eval origin string we get from V8 looks like
// `eval at ${function_name} (${origin})`
// where origin can be either a file name, like
// "eval at foo (file:///path/to/script.ts:1:2)"
// or a nested eval origin, like
// "eval at foo (eval at bar (file:///path/to/script.ts:1:2))"
//
let eval_at = "eval at ";
// only the innermost eval origin can have location info, so find the last
// "eval at", then continue parsing the rest of the string
let mut innermost_start = eval_origin.rfind(eval_at)? + eval_at.len();
// skip over the function name
innermost_start += eval_origin[innermost_start..].find('(')? + 1;
if innermost_start >= eval_origin.len() {
// malformed
return None;
}
// from the right, split by ":" to get the column number, line number, file name
// (in that order, since we're iterating from the right). e.g.
// eval at foo (eval at bar (file://foo.ts:1:2))
// ^^^^^^^^^^^^^ ^ ^^^
let mut parts = eval_origin[innermost_start..].rsplitn(3, ':');
// the part with the column number will include extra stuff, the actual number ends at
// the closing paren
let column_number_with_rest = parts.next()?;
let column_number_end = column_number_with_rest.find(')')?;
let column_number = column_number_with_rest[..column_number_end]
.parse::<i64>()
.ok()?;
let line_number = parts.next()?.parse::<i64>().ok()?;
let file_name = parts.next()?;
// The column number starts after the last occurring ":".
let column_start = eval_origin.rfind(':')? + 1;
// the innermost origin ends at the end of the column number
let innermost_end = column_start + column_number_end;
Some((
&eval_origin[..innermost_start],
(file_name, line_number, column_number),
&eval_origin[innermost_end..],
))
}
impl JsStackFrame {
pub fn from_location(
file_name: Option<String>,
line_number: Option<i64>,
column_number: Option<i64>,
) -> Self {
Self {
type_name: None,
function_name: None,
method_name: None,
file_name,
line_number,
column_number,
eval_origin: None,
is_top_level: None,
is_eval: false,
is_native: false,
is_constructor: false,
is_async: false,
is_promise_all: false,
is_wasm: false,
promise_index: None,
}
}
/// Creates a `JsStackFrame` from a `CallSite`` JS object,
/// provided by V8.
fn from_callsite_object<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
callsite: v8::Local<'s, v8::Object>,
) -> Option<Self> {
macro_rules! call {
($key: ident : $t: ty) => {{
let res = call_method(scope, callsite, $key, &[])?;
let res: $t = match serde_v8::from_v8(scope, res) {
Ok(res) => res,
Err(err) => {
let message = format!(
"Failed to deserialize return value from callsite property '{}' to correct type: {err:?}.",
$key
);
let message = v8::String::new(scope, &message).unwrap();
let exception = v8::Exception::type_error(scope, message);
scope.throw_exception(exception);
return None;
}
};
res
}};
($key: ident) => { call!($key : _) };
}
let raw_file_name = call!(GET_FILE_NAME : Option<String>);
let is_wasm = raw_file_name
.as_deref()
.map(|f| f.starts_with("wasm://"))
.unwrap_or(false);
// For wasm frames, skip source map application — source maps don't apply to wasm.
// V8 returns the function index via getLineNumber() and byte offset via getColumnNumber().
let (file_name, line_number, column_number) = if is_wasm {
(
raw_file_name,
call!(GET_LINE_NUMBER),
call!(GET_COLUMN_NUMBER),
)
} else {
let state = JsRuntime::state_from(scope);
let mut source_mapper = state.source_mapper.borrow_mut();
// apply source map
match (
raw_file_name,
call!(GET_LINE_NUMBER),
call!(GET_COLUMN_NUMBER),
) {
(Some(f), Some(l), Some(c)) => {
let (file_name, line_num, col_num) =
apply_source_map(&mut source_mapper, f.into(), l, c);
(Some(file_name.into_owned()), Some(line_num), Some(col_num))
}
(f, l, c) => (f, l, c),
}
};
// apply source map to the eval origin, if the error originates from `eval`ed code
let eval_origin = if is_wasm {
None
} else {
call!(GET_EVAL_ORIGIN: Option<String>).and_then(|o| {
let Some((before, (file, line, col), after)) = parse_eval_origin(&o)
else {
return Some(o);
};
let state = JsRuntime::state_from(scope);
let mut source_mapper = state.source_mapper.borrow_mut();
let (file, line, col) =
apply_source_map(&mut source_mapper, file.into(), line, col);
Some(format!("{before}{file}:{line}:{col}{after}"))
})
};
Some(Self {
file_name,
line_number,
column_number,
eval_origin,
type_name: call!(GET_TYPE_NAME),
function_name: call!(GET_FUNCTION_NAME),
method_name: call!(GET_METHOD_NAME),
is_top_level: call!(IS_TOPLEVEL),
is_eval: call!(IS_EVAL),
is_native: call!(IS_NATIVE),
is_constructor: call!(IS_CONSTRUCTOR),
is_async: call!(IS_ASYNC),
is_promise_all: call!(IS_PROMISE_ALL),
is_wasm,
promise_index: call!(GET_PROMISE_INDEX),
})
}
/// Gets the source mapped stack frame corresponding to the
/// (script_resource_name, line_number, column_number) from a v8 message.
/// For non-syntax errors, it should also correspond to the first stack frame.
pub fn from_v8_message<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
message: v8::Local<'s, v8::Message>,
) -> Option<Self> {
let f = message.get_script_resource_name(scope)?;
let f: v8::Local<v8::String> = f.try_into().ok()?;
let f = f.to_rust_string_lossy(scope);
let l = message.get_line_number(scope)? as i64;
// V8's column numbers are 0-based, we want 1-based.
let c = message.get_start_column() as i64 + 1;
let state = JsRuntime::state_from(scope);
let mut source_mapper = state.source_mapper.borrow_mut();
let (file_name, line_num, col_num) =
apply_source_map(&mut source_mapper, f.into(), l, c);
Some(JsStackFrame::from_location(
Some(file_name.into_owned()),
Some(line_num),
Some(col_num),
))
}
pub fn maybe_format_location(&self) -> Option<String> {
Some(format!(
"{}:{}:{}",
self.file_name.as_ref()?,
self.line_number?,
self.column_number?
))
}
}
#[inline(always)]
fn get_property<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
object: v8::Local<'s, v8::Object>,
key: FastStaticString,
) -> Option<v8::Local<'s, v8::Value>> {
let key = key.v8_string(scope).unwrap();
object.get(scope, key.into())
}
fn call_method<'s, 'i, T>(
scope: &mut v8::PinScope<'s, 'i>,
object: v8::Local<'s, v8::Object>,
key: FastStaticString,
args: &[v8::Local<'s, v8::Value>],
) -> Option<v8::Local<'s, T>>
where
v8::Local<'s, T>: TryFrom<v8::Local<'s, v8::Value>, Error: Debug>,
{
let func = match get_property(scope, object, key)?.try_cast::<v8::Function>()
{
Ok(func) => func,
Err(err) => {
let message =
format!("Callsite property '{key}' is not a function: {err}");
let message = v8::String::new(scope, &message).unwrap();
let exception = v8::Exception::type_error(scope, message);
scope.throw_exception(exception);
return None;
}
};
let res = func.call(scope, object.into(), args)?;
let result = match v8::Local::try_from(res) {
Ok(result) => result,
Err(err) => {
let message = format!(
"Failed to cast callsite method '{key}' return value to correct value: {err:?}."
);
let message = v8::String::new(scope, &message).unwrap();
let exception = v8::Exception::type_error(scope, message);
scope.throw_exception(exception);
return None;
}
};
Some(result)
}
#[derive(Debug, Default, serde::Deserialize)]
pub(crate) struct NativeJsError {
pub name: Option<String>,
pub message: Option<String>,
// Warning! .stack is special so handled by itself
// stack: Option<String>,
}
impl JsError {
/// Compares all properties of JsError, except for JsError::cause. This function is used to
/// detect that 2 JsError objects in a JsError::cause chain are identical, ie. there is a recursive cause.
///
/// We don't have access to object identity here, so we do it via field comparison. Ideally this should
/// be able to maintain object identity somehow.
pub fn is_same_error(&self, other: &JsError) -> bool {
let a = self;
let b = other;
// `a.cause == b.cause` omitted, because it is absent in recursive errors,
// despite the error being identical to a previously seen one.
a.name == b.name
&& a.message == b.message
&& a.stack == b.stack
// TODO(mmastrac): we need consistency around when we insert "in promise" and when we don't. For now, we
// are going to manually replace this part of the string.
&& (a.exception_message == b.exception_message
|| a.exception_message.replace(" (in promise) ", " ") == b.exception_message.replace(" (in promise) ", " "))
&& a.frames == b.frames
&& a.source_line == b.source_line
&& a.source_line_frame_index == b.source_line_frame_index
&& a.aggregated == b.aggregated
}
pub fn from_v8_exception<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
exception: v8::Local<'s, v8::Value>,
) -> Box<Self> {
Box::new(Self::inner_from_v8_exception(
scope,
exception,
Default::default(),
))
}
pub fn from_v8_message<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
msg: v8::Local<'s, v8::Message>,
) -> Box<Self> {
// Create a new HandleScope because we're creating a lot of new local
// handles below.
v8::scope!(let scope, scope);
let exception_message = msg.get(scope).to_rust_string_lossy(scope);
// Convert them into Vec<JsStackFrame>
let mut frames: Vec<JsStackFrame> = vec![];
let mut source_line = None;
let mut source_line_frame_index = None;
if let Some(stack_frame) = JsStackFrame::from_v8_message(scope, msg) {
frames = vec![stack_frame];
}
{
let state = JsRuntime::state_from(scope);
let mut source_mapper = state.source_mapper.borrow_mut();
for (i, frame) in frames.iter().enumerate() {
if let (Some(file_name), Some(line_number)) =
(&frame.file_name, frame.line_number)
&& !file_name.trim_start_matches('[').starts_with("ext:")
{
source_line = source_mapper.get_source_line(file_name, line_number);
source_line_frame_index = Some(i);
break;
}
}
}
Box::new(Self {
name: None,
message: None,
exception_message,
cause: None,
source_line,
source_line_frame_index,
frames,
stack: None,
aggregated: None,
additional_properties: vec![],
})
}
fn inner_from_v8_exception<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
exception: v8::Local<'s, v8::Value>,
mut seen: HashSet<v8::Local<'s, v8::Object>>,
) -> Self {
// Create a new HandleScope because we're creating a lot of new local
// handles below.
v8::scope!(let scope, scope);
let msg = v8::Exception::create_message(scope, exception);
let mut exception_message = None;
let exception_state = JsRealm::exception_state_from_scope(scope);
let js_format_exception_cb =
exception_state.js_format_exception_cb.borrow().clone();
if let Some(format_exception_cb) = js_format_exception_cb {
let format_exception_cb = format_exception_cb.open(scope);
let this = v8::undefined(scope).into();
let formatted = format_exception_cb.call(scope, this, &[exception]);
if let Some(formatted) = formatted
&& formatted.is_string()
{
exception_message = Some(formatted.to_rust_string_lossy(scope));
}
}
if is_instance_of_error(scope, exception) {
let v8_exception = exception;
// The exception is a JS Error object.
let exception: v8::Local<v8::Object> = exception.try_into().unwrap();
let cause = get_property(scope, exception, v8_static_strings::CAUSE);
let e: NativeJsError =
serde_v8::from_v8(scope, exception.into()).unwrap_or_default();
// Get the message by formatting error.name and error.message.
let name = e.name.clone().unwrap_or_else(|| GENERIC_ERROR.to_string());
let message_prop = e.message.clone().unwrap_or_default();
let exception_message = exception_message.unwrap_or_else(|| {
if !name.is_empty() && !message_prop.is_empty() {
format!("Uncaught {name}: {message_prop}")
} else if !name.is_empty() {
format!("Uncaught {name}")
} else if !message_prop.is_empty() {
format!("Uncaught {message_prop}")
} else {
"Uncaught".to_string()
}
});
let cause = cause.and_then(|cause| {
if cause.is_undefined() || seen.contains(&exception) {
None
} else {
seen.insert(exception);
Some(Box::new(JsError::inner_from_v8_exception(
scope, cause, seen,
)))
}
});
// Access error.stack to ensure that prepareStackTrace() has been called.
// This should populate error.#callSiteEvals.
let stack = get_property(scope, exception, v8_static_strings::STACK);
let stack: Option<v8::Local<v8::String>> =
stack.and_then(|s| s.try_into().ok());
let stack = stack.map(|s| s.to_rust_string_lossy(scope));
// Read an array of structured frames from error.#callSiteEvals.
let frames_v8 = {
let key = call_site_evals_key(scope);
exception.get_private(scope, key)
};
// Ignore non-array values
let frames_v8: Option<v8::Local<v8::Array>> =
frames_v8.and_then(|a| a.try_into().ok());
// Convert them into Vec<JsStackFrame>
let mut frames: Vec<JsStackFrame> = match frames_v8 {
Some(frames_v8) => {
let mut buf = Vec::with_capacity(frames_v8.length() as usize);
for i in 0..frames_v8.length() {
let callsite = frames_v8.get_index(scope, i).unwrap().cast();
v8::tc_scope!(let tc_scope, scope);
let Some(stack_frame) =
JsStackFrame::from_callsite_object(tc_scope, callsite)
else {
let message = tc_scope
.exception()
.expect(
"JsStackFrame::from_callsite_object raised an exception",
)
.to_rust_string_lossy(tc_scope);
#[allow(clippy::print_stderr)]
{
eprintln!(
"warning: Failed to create JsStackFrame from callsite object: {message}. This is a bug in deno"
);
}
break;
};
buf.push(stack_frame);
}
buf
}
None => vec![],
};
let mut source_line = None;
let mut source_line_frame_index = None;
// When the stack frame array is empty, but the source location given by
// (script_resource_name, line_number, start_column + 1) exists, this is
// likely a syntax error. For the sake of formatting we treat it like it
// was given as a single stack frame.
if frames.is_empty()
&& let Some(stack_frame) = JsStackFrame::from_v8_message(scope, msg)
{
frames = vec![stack_frame];
}
{
let state = JsRuntime::state_from(scope);
let mut source_mapper = state.source_mapper.borrow_mut();
for (i, frame) in frames.iter().enumerate() {
if let (Some(file_name), Some(line_number)) =
(&frame.file_name, frame.line_number)
&& !file_name.trim_start_matches('[').starts_with("ext:")
{
source_line = source_mapper.get_source_line(file_name, line_number);
source_line_frame_index = Some(i);
break;
}
}
}
let mut aggregated: Option<Vec<JsError>> = None;
if is_aggregate_error(scope, v8_exception) {
// Read an array of stored errors, this is only defined for `AggregateError`
let aggregated_errors =
get_property(scope, exception, v8_static_strings::ERRORS);
let aggregated_errors: Option<v8::Local<v8::Array>> =
aggregated_errors.and_then(|a| a.try_into().ok());
if let Some(errors) = aggregated_errors
&& errors.length() > 0
{
let mut agg = vec![];
for i in 0..errors.length() {
let error = errors.get_index(scope, i).unwrap();
let js_error = Self::from_v8_exception(scope, error);
agg.push(*js_error);
}
aggregated = Some(agg);
}
};
let additional_properties_string =
v8::String::new(scope, "errorAdditionalPropertyKeys").unwrap();
let additional_properties_key =
v8::Symbol::for_key(scope, additional_properties_string);
let additional_properties =
exception.get(scope, additional_properties_key.into());
let additional_properties = if let Some(arr) =
additional_properties.and_then(|keys| keys.try_cast::<v8::Array>().ok())
{
let mut out = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
let Some(key) = arr.get_index(scope, i) else {
continue;