-
-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathstringify-error.mjs
More file actions
50 lines (46 loc) · 1.36 KB
/
stringify-error.mjs
File metadata and controls
50 lines (46 loc) · 1.36 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
// @ts-check
/**
* Regular expression for matching line endings.
*/
const newlineRe = /\r\n?|\n/g;
/**
* Converts a string to an array of indented lines.
* @param {String} string String to convert.
* @returns {String[]} Array of indented lines.
*/
function toIndentedLines (string) {
return string.split(newlineRe).map((line) => ` ${line}`);
}
/**
* String-ifies an Error (or AggregateError) object.
* @param {Error} error Error object to string-ify.
* @returns {String} Error details.
*/
function stringifyError (error) {
const name = error?.name || "[NO NAME]";
const message = error?.message || JSON.stringify(error);
const stack = error?.stack || "[NO STACK]";
// @ts-ignore
const cause = error?.cause;
// @ts-ignore
const errors = error?.errors || [];
const result = [ `${name}: ${message}`, "stack:" ];
const frames = stack.split(newlineRe);
const discardFrame = (frames[0] === result[0]);
for (const frame of frames.slice(discardFrame ? 1 : 0)) {
result.push(` ${frame.trim()}`);
}
if (cause) {
result.push("cause:");
// eslint-disable-next-line unicorn/prefer-single-call
result.push(...toIndentedLines(stringifyError(cause)));
}
if (errors.length > 0) {
result.push("errors:");
for (const subError of errors) {
result.push(...toIndentedLines(stringifyError(subError)));
}
}
return result.join("\n");
}
export default stringifyError;