-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_object.ts
66 lines (62 loc) · 1.36 KB
/
error_object.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
import { isString } from "@core/unknownutil/is/string";
import { isRecord } from "@core/unknownutil/is/record";
import { isObjectOf } from "@core/unknownutil/is/object-of";
import { asOptional } from "@core/unknownutil/as/optional";
/**
* An error object is a serializable representation of an error
*/
export type ErrorObject = {
/**
* The name of the error prototype
*/
proto: string;
/**
* The name of the error
*/
name: string;
/**
* The error message
*/
message: string;
/**
* The error stack
*/
stack?: string;
/**
* Additional attributes
*/
attributes: Record<string, unknown>;
};
/**
* Check if a value is an error object
*/
export const isErrorObject: (x: unknown) => x is ErrorObject = isObjectOf({
proto: isString,
name: isString,
message: isString,
stack: asOptional(isString),
attributes: isRecord,
});
/**
* Convert an error to an error object
*/
export function toErrorObject(err: Error): ErrorObject {
const { constructor, name, message, stack = undefined, ...rest } = err;
return {
proto: constructor.name,
name,
message,
stack,
attributes: rest,
};
}
/**
* Convert an error object to an error
*/
export function fromErrorObject(obj: ErrorObject): Error {
return Object.assign(new Error(obj.message), {
name: obj.name,
stack: obj.stack,
...obj.attributes,
});
}