-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy patherror.rs
More file actions
348 lines (300 loc) · 11.4 KB
/
Copy patherror.rs
File metadata and controls
348 lines (300 loc) · 11.4 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
//! Contains the error type for the runtime
//! And some associated utilities
use std::path::PathBuf;
use deno_core::error::CoreErrorKind;
use thiserror::Error;
use crate::Module;
/// Options for [`Error::as_highlighted`]
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone)]
pub struct ErrorFormattingOptions {
/// Include the filename in the output
/// Appears on the first line
pub include_filename: bool,
/// Include the line number in the output
/// Appears on the first line
pub include_line_number: bool,
/// Include the column number in the output
/// Appears on the first line
pub include_column_number: bool,
/// Hide the current directory in the output
pub hide_current_directory: bool,
/// Used to set the directory to remove, in cases where the runtime and system CWD differ
pub current_directory: Option<PathBuf>,
}
impl Default for ErrorFormattingOptions {
fn default() -> Self {
Self {
include_filename: true,
include_line_number: true,
include_column_number: true,
hide_current_directory: false,
current_directory: None,
}
}
}
/// Represents the errors that can occur during execution of a module
#[derive(Error, Debug, Clone, serde::Serialize, serde::Deserialize, deno_error::JsError)]
pub enum Error {
/// Triggers when a module has no stated entrypoint (default or registered at runtime)
#[class(generic)]
#[error("{0} has no entrypoint. Register one, or add a default to the runtime")]
MissingEntrypoint(Module),
/// Triggers when an attempt to find a value by name fails
#[class(generic)]
#[error("{0} could not be found in global, or module exports")]
ValueNotFound(String),
/// Triggers when attempting to call a value as a function
#[class(generic)]
#[error("{0} is not a function")]
ValueNotCallable(String),
/// Triggers when a string could not be encoded for v8
#[class(generic)]
#[error("{0} could not be encoded as a v8 value")]
V8Encoding(String),
/// Triggers when a result could not be deserialize to the requested type
#[class(generic)]
#[error("value could not be deserialized: {0}")]
JsonDecode(String),
/// Triggers when a module could not be loaded from the filesystem
#[class(generic)]
#[error("{0}")]
ModuleNotFound(String),
/// Triggers when attempting to use a worker that has already been shutdown
#[class(generic)]
#[error("This worker has been destroyed")]
WorkerHasStopped,
/// Triggers on runtime issues during execution of a module
#[class(generic)]
#[error("{0}")]
Runtime(String),
/// Runtime error we successfully downcast
#[class(generic)]
#[error("{0}")]
JsError(Box<deno_core::error::JsError>),
/// Triggers when a module times out before finishing
#[class(generic)]
#[error("Module timed out: {0}")]
Timeout(String),
/// Triggers when the heap (via `max_heap_size`) is exhausted during execution
#[class(generic)]
#[error("Heap exhausted")]
HeapExhausted,
}
impl From<deno_core::error::JsError> for Error {
fn from(err: deno_core::error::JsError) -> Self {
Self::JsError(Box::new(err))
}
}
impl From<Box<deno_core::error::JsError>> for Error {
fn from(err: Box<deno_core::error::JsError>) -> Self {
Self::JsError(err)
}
}
impl Error {
/// Formats an error for display in a terminal
/// If the error is a `JsError`, it will attempt to highlight the source line
/// in this format:
/// ```text
/// | let x = 1 + 2
/// | ^
/// = Unexpected token '='
/// ```
///
/// Otherwise, it will just display the error message normally
#[must_use]
pub fn as_highlighted(&self, options: ErrorFormattingOptions) -> String {
let mut e = if let Error::JsError(e) = self {
// Extract basic information about position
let (filename, row, col) = match e.frames.first() {
Some(f) => (
match &f.file_name {
Some(f) if f.is_empty() => None::<&str>,
Some(f) => Some(f.as_ref()),
None => None,
},
usize::try_from(f.line_number.unwrap_or(1)).unwrap_or_default(),
usize::try_from(f.column_number.unwrap_or(1)).unwrap_or_default(),
),
None => (None, 1, 1),
};
let mut line = e.source_line.as_ref().map(|s| s.trim_end());
let col = col.saturating_sub(1);
// Get at most 50 characters, centered on column_number
let mut padding = String::new();
match line {
None => {}
Some(s) => {
let (start, end) = if s.len() < 50 {
(0, s.len())
} else if col < 25 {
(0, 50)
} else if col > s.len() - 25 {
(s.len() - 50, s.len())
} else {
(col - 25, col + 25)
};
line = Some(s.get(start..end).unwrap_or(s));
padding = " ".repeat(col - start);
}
}
let msg_lines = e.exception_message.split('\n').collect::<Vec<_>>();
//
// Format all the parts using the options
//
let line_number_part = if options.include_line_number {
format!("{row}:")
} else {
String::new()
};
let col_number_part = if options.include_column_number {
format!("{col}:")
} else {
String::new()
};
let source_line_part = match line {
Some(s) => format!("| {s}\n| {padding}^\n"),
None => String::new(),
};
let msg_part = msg_lines
.into_iter()
.map(|l| format!("= {l}"))
.collect::<Vec<_>>()
.join("\n");
let position_part = format!("{line_number_part}{col_number_part}");
let position_part = match filename {
None if position_part.is_empty() => String::new(),
Some(f) if options.include_filename => format!("At {f}:{position_part}\n"),
_ => format!("At {position_part}\n"),
};
// Combine all the parts
format!("{position_part}{source_line_part}{msg_part}",)
} else {
self.to_string()
};
//
// Hide directory
if options.hide_current_directory {
let dir = options.current_directory.or(std::env::current_dir().ok());
if let Some(dir) = dir {
let dir = dir.to_string_lossy().replace('\\', "/");
e = e.replace(&dir, "");
e = e.replace("file:////", "file:///");
}
}
e
}
}
#[macro_use]
mod error_macro {
/// Maps one error type to another
macro_rules! map_error {
($source_error:path, $impl:expr) => {
impl From<$source_error> for Error {
fn from(e: $source_error) -> Self {
let fmt: &dyn Fn($source_error) -> Self = &$impl;
fmt(e)
}
}
};
}
}
#[cfg(feature = "node_experimental")]
map_error!(node_resolver::analyze::TranslateCjsToEsmError, |e| {
Error::Runtime(e.to_string())
});
map_error!(deno_ast::TranspileError, |e| Error::Runtime(e.to_string()));
map_error!(deno_core::error::CoreError, |e| {
let e = e.into_kind();
match e {
CoreErrorKind::Js(js_error) => Error::JsError(js_error),
_ => Error::Runtime(e.to_string()),
}
});
map_error!(std::cell::BorrowMutError, |e| Error::Runtime(e.to_string()));
map_error!(std::io::Error, |e| Error::ModuleNotFound(e.to_string()));
map_error!(deno_core::v8::DataError, |e| Error::Runtime(e.to_string()));
map_error!(deno_core::ModuleResolutionError, |e| Error::Runtime(
e.to_string()
));
map_error!(deno_core::url::ParseError, |e| Error::Runtime(
e.to_string()
));
map_error!(deno_core::serde_json::Error, |e| Error::JsonDecode(
e.to_string()
));
map_error!(deno_core::serde_v8::Error, |e| Error::JsonDecode(
e.to_string()
));
map_error!(deno_core::anyhow::Error, |e| {
Error::Runtime(e.to_string())
});
map_error!(tokio::time::error::Elapsed, |e| {
Error::Timeout(e.to_string())
});
map_error!(tokio::task::JoinError, |e| {
Error::Timeout(e.to_string())
});
map_error!(deno_core::futures::channel::oneshot::Canceled, |e| {
Error::Timeout(e.to_string())
});
// Note: BroadcastChannelError mapping removed - no longer exported from deno_web
#[cfg(test)]
mod test {
use crate::{error::ErrorFormattingOptions, Module, Runtime, RuntimeOptions, Undefined};
#[test]
#[rustfmt::skip]
fn test_highlights() {
let mut runtime = Runtime::new(RuntimeOptions::default()).unwrap();
let e = runtime.eval::<Undefined>("1+1;\n1 + x").unwrap_err().as_highlighted(ErrorFormattingOptions::default());
assert_eq!(e, concat!(
"At 2:4:\n",
"= Uncaught ReferenceError: x is not defined"
));
let module = Module::new("test.js", "1+1;\n1 + x");
let e = runtime.load_module(&module).unwrap_err().as_highlighted(ErrorFormattingOptions {
include_filename: false,
..Default::default()
});
assert_eq!(e, concat!(
"At 2:4:\n",
"| 1 + x\n",
"| ^\n",
"= Uncaught (in promise) ReferenceError: x is not defined"
));
let module = Module::new("test.js", "1+1;\n1 + x");
let e = runtime.load_module(&module).unwrap_err().as_highlighted(ErrorFormattingOptions {
hide_current_directory: true,
..Default::default()
});
assert_eq!(e, concat!(
"At file:///test.js:2:4:\n",
"| 1 + x\n",
"| ^\n",
"= Uncaught (in promise) ReferenceError: x is not defined"
));
}
#[test]
fn highlight_with_zero_column_does_not_panic() {
let js_error = deno_core::error::JsError {
name: Some("ReferenceError".to_string()),
message: Some("x is not defined".to_string()),
stack: None,
cause: None,
exception_message: "Uncaught ReferenceError: x is not defined".to_string(),
frames: vec![deno_core::error::JsStackFrame::from_location(
Some("file:///test.js".to_string()),
Some(1),
Some(0),
)],
source_line: Some("const x = y;".to_string()),
source_line_frame_index: Some(0),
aggregated: None,
additional_properties: vec![],
};
let err = crate::Error::from(Box::new(js_error));
let out = err.as_highlighted(ErrorFormattingOptions::default());
assert!(out.contains("const x = y;"));
assert!(out.contains("ReferenceError"));
}
}