-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathensure-error.ts
48 lines (38 loc) · 1011 Bytes
/
ensure-error.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
// Derived from: https://github.com/sindresorhus/ensure-error
// but uses JSON.stringify instead of util.inspect for browser compatibility
class NonError extends Error {
name = "NonError";
constructor(message: unknown) {
super(JSON.stringify(message));
}
}
export default function ensureError(input: unknown) {
if (!(input instanceof Error)) {
return new NonError(input);
}
const error = input;
if (!error.name) {
Object.defineProperty(error, "name", {
value: error.constructor?.name || "Error",
configurable: true,
writable: true,
});
}
if (!error.message) {
Object.defineProperty(error, "message", {
value: "<No error message>",
configurable: true,
writable: true,
});
}
if (!error.stack) {
const newErr = new Error(error.message);
newErr.stack = newErr.stack || "";
Object.defineProperty(error, "stack", {
value: newErr.stack.replace(/\n {4}at /, "\n<Original stack missing>$&"),
configurable: true,
writable: true,
});
}
return error;
}