/
errors.ts
261 lines (219 loc) Β· 6.64 KB
/
errors.ts
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
import { bold, cyan, dim, red, yellow } from "../deps/colors.ts";
import { fromFileUrl } from "../deps/path.ts";
import type { Page } from "../core.ts";
/** Error payload interface */
export interface ErrorData {
cause?: Error;
name?: string;
mark?: Mark;
[key: string]: unknown;
}
/** Parsed stacktraces */
export interface Mark {
name?: string;
file?: string;
line?: number;
column?: number;
code?: string;
}
/**
* Generic Exception to throw errors.
* It allows to include extra data.
*/
export class Exception extends Error {
data?: Record<string, unknown>;
mark?: Mark;
constructor(message: string, data: ErrorData = {}) {
const options = data.cause ? { cause: data.cause } : {};
delete data.cause;
super(message, options);
if (data.name) {
this.name = data.name;
delete data.name;
}
if (data.mark) {
this.mark = data.mark;
delete data.mark;
}
this.data = data;
}
}
/** Pretty-print an Error or Exception instance */
export function printError(error: unknown, caused = false) {
console.log();
// Print the error message
if (caused) {
if (error instanceof Error) {
console.error(`Caused by ${bold(red(`${error.name}:`))}`, error.message);
} else {
console.error(`Caused by:`, error);
}
} else {
if (error instanceof Error) {
console.error(`${bold(red(`${error.name}:`))}`, error.message);
} else {
console.error(error);
}
}
// Print the data and mark of Exception instances
if (error instanceof Exception) {
if (error.mark) {
const { mark } = error;
const code = getCode(mark);
if (code && mark.file && mark.line && mark.column) {
console.log(
` at ${cyan(mark.file)}:${yellow(mark.line.toString())}:${
yellow(mark.column.toString())
}`,
);
console.log(code);
}
}
for (let [key, value] of Object.entries(error.data ?? {})) {
if (key === "page") {
const src = (value as Page).src;
value = src.path + src.ext;
if (src.remote) {
value += ` (remote: ${src.remote})`;
}
}
console.log(dim(`- ${key}:`), value);
}
}
// Print the error stack
if (error instanceof Error && error.stack) {
const marks = parseStack(error);
marks.forEach((mark) => {
const log: string[] = ["at"];
let code: string | undefined;
if (mark.name) {
log.push(bold(mark.name));
}
if (mark.file) {
if (mark.line && mark.column) {
log.push(
`(${cyan(mark.file)}:${yellow(mark.line.toString())}:${
yellow(mark.column.toString())
})`,
);
try {
const path = fromFileUrl(mark.file);
if (path.startsWith(cwd)) {
code = getCode(mark);
}
} catch {
// Do nothing
}
} else {
log.push(`(${cyan(mark.file)})`);
}
}
console.log(" ", log.join(" "));
if (code) {
console.log(code);
console.log();
}
});
}
// Print the error cause
if (error instanceof Error && error.cause) {
printError(error.cause, true);
}
}
const cwd = Deno.cwd();
/** Read the errored code from a mark */
function getCode(mark: Mark): string | undefined {
if (!mark.file || !mark.line || !mark.column) {
return;
}
try {
const { line, column } = mark;
let content = mark.code;
if (content === undefined) {
const path = mark.file.startsWith("file://")
? fromFileUrl(mark.file)
: mark.file;
if (!path.startsWith(cwd)) {
return;
}
content = Deno.readTextFileSync(path);
}
const code: string[] = [];
const lines = content.split("\n");
if (lines[line - 2]) {
code.push(` ${dim(`| ${line - 1} |`)} ${lines[line - 2]}`);
}
code.push(
` ${dim(`| ${bold(red(line.toString()))} |`)} ${
bold(lines[line - 1])
}`,
` ${dim(`| ${bold(red("~".repeat(line.toString().length)))} |`)} ${
red("~".repeat(column - 1) + "^")
}`,
);
if (lines[line]) {
code.push(` ${dim(`| ${line + 1} |`)} ${lines[line]}`);
}
return code.join("\n");
} catch {
// Do nothing
}
}
/**
* Function to parse the stacktrace
* Code from: https://github.com/stacktracejs/stacktrace.js/blob/master/dist/stacktrace.js
*/
export function parseStack(error: Error): Mark[] {
const lines =
error.stack?.split("\n").filter((line) =>
!!line.match(/^\s*at .*(\S+:\d+|\(native\))/m)
) || [];
return lines.map(function (line): Mark {
if (line.indexOf("(eval ") > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line.replace(/eval code/g, "eval").replace(
/(\(eval at [^()]*)|(\),.*$)/g,
"",
);
}
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(");
// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
// case it has spaces in it, as the string is split on \s+ later on
const location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);
// remove the parenthesized location from the line, if it was matched
sanitizedLine = location
? sanitizedLine.replace(location[0], "")
: sanitizedLine;
const tokens = sanitizedLine.split(/\s+/).slice(1);
// if a location was matched, pass it to extractLocation() otherwise pop the last token
const locationString = location ? location[1] : tokens.pop();
const locationParts = locationString ? extractLocation(locationString) : [];
const functionName = tokens.join(" ") || undefined;
const fileName = ["eval", "<anonymous>"].indexOf(locationParts[0]) > -1
? undefined
: locationParts[0];
return {
name: functionName,
file: fileName?.replace(/#.*$/, ""), // Removed hash from file path
line: locationParts[1] ? parseInt(locationParts[1]) : undefined,
column: locationParts[2] ? parseInt(locationParts[2]) : undefined,
};
});
}
/**
* Separate line and column numbers from a string of the form: (URI:Line:Column)
* Code from: https://github.com/stacktracejs/stacktrace.js/blob/master/dist/stacktrace.js
*/
export function extractLocation(source: string): [string, string?, string?] {
// Fail-fast but return locations like "(native)"
if (source.indexOf(":") === -1) {
return [source];
}
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
const parts = regExp.exec(source.replace(/[()]/g, ""));
if (!parts) {
return [source];
}
const [, path, line, column] = parts;
return [path, line, column];
}