-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
84 lines (75 loc) · 2.1 KB
/
index.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
/*!
* Return a function that will copy properties from
* one object to another excluding any originally
* listed. Returned function will create a new `{}`.
*
* @param {String} excluded properties ...
* @return {Function}
*/
function exclude(...excludes: any[]) {
function excludeProps(res: object, obj: object) {
for (const key of Object.keys(obj)) {
if (!~excludes.indexOf(key)) res[key] = obj[key];
}
}
return function extendExclude(...args: any[]) {
let i = 0,
res = {};
for (; i < args.length; i++) {
excludeProps(res, args[i]);
}
return res;
};
}
export class AssertionError<T = {}> extends Error {
name = "AssertionError";
showDiff: boolean;
/**
* ### AssertionError
*
* An extension of the JavaScript `Error` constructor for
* assertion and validation scenarios.
*
* @param {String} message
* @param {Object} properties to include (optional)
* @param {callee} start stack function (optional)
*/
constructor(message?: string, _props?: T, ssf?: Function) {
super();
let extend = exclude("name", "message", "stack", "constructor", "toJSON"),
props = extend(_props || {});
// default values
this.message = message || "Unspecified AssertionError";
this.showDiff = false;
// copy from properties
for (const key in props) {
this[key] = props[key];
}
// capture stack trace
ssf = ssf || AssertionError;
if (Error["captureStackTrace"]) {
Error["captureStackTrace"](this, ssf);
} else {
try {
throw new Error();
} catch (e) {
this.stack = e.stack;
}
}
}
/**
* Allow errors to be converted to JSON for static transfer.
*
* @param {Boolean} include stack (default: `true`)
* @return {Object} object that can be `JSON.stringify`
*/
toJSON(stack?: boolean): object {
let extend = exclude("constructor", "toJSON", "stack"),
props = extend({ name: this.name }, this);
// include stack if exists and not turned off
if (false !== stack && this.stack) {
props["stack"] = this.stack;
}
return props;
}
}