|
| 1 | +/** |
| 2 | + * Return a function that will copy properties from |
| 3 | + * one object to another excluding any originally |
| 4 | + * listed. Returned function will create a new `{}`. |
| 5 | + * |
| 6 | + * @param {String} excluded properties ... |
| 7 | + * @return {Function} |
| 8 | + */ |
| 9 | +function exclude(...args: string[]): (a: {}, b?: {}) => Record<string, unknown> { |
| 10 | + var excludes = args |
| 11 | + |
| 12 | + function excludeProps (res: Record<string, unknown>, obj: Record<string, unknown>) { |
| 13 | + Object.keys(obj).forEach(function (key) { |
| 14 | + if (!~excludes.indexOf(key)) res[key] = obj[key]; |
| 15 | + }); |
| 16 | + } |
| 17 | + |
| 18 | + return function extendExclude () { |
| 19 | + var args = [].slice.call(arguments) |
| 20 | + , i = 0 |
| 21 | + , res = {}; |
| 22 | + |
| 23 | + for (; i < args.length; i++) { |
| 24 | + excludeProps(res, args[i]); |
| 25 | + } |
| 26 | + |
| 27 | + return res; |
| 28 | + }; |
| 29 | +}; |
| 30 | + |
| 31 | +export default class AssertionError<T> extends Error { |
| 32 | + name = 'AssertionError' |
| 33 | + showDiff: boolean |
| 34 | + [key: string]: any |
| 35 | + |
| 36 | + constructor(message: string, _props?: T, ssf?: Function) { |
| 37 | + super() |
| 38 | + var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON') |
| 39 | + , props = extend(_props || {}); |
| 40 | + |
| 41 | + // default values |
| 42 | + this.message = message || 'Unspecified AssertionError'; |
| 43 | + this.showDiff = false; |
| 44 | + |
| 45 | + // copy from properties |
| 46 | + for (var key in props) { |
| 47 | + this[key] = props[key]; |
| 48 | + } |
| 49 | + |
| 50 | + // capture stack trace |
| 51 | + ssf = ssf || AssertionError; |
| 52 | + if ((Error as any).captureStackTrace) { |
| 53 | + (Error as any).captureStackTrace(this, ssf); |
| 54 | + } else { |
| 55 | + try { |
| 56 | + throw new Error(); |
| 57 | + } catch(e: any) { |
| 58 | + this.stack = e.stack; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Allow errors to be converted to JSON for static transfer. |
| 65 | + * |
| 66 | + * @param {Boolean} include stack (default: `true`) |
| 67 | + * @return {Object} object that can be `JSON.stringify` |
| 68 | + */ |
| 69 | + |
| 70 | + toJSON(stack: boolean) { |
| 71 | + var extend = exclude('constructor', 'toJSON', 'stack') |
| 72 | + , props = extend({ name: this.name }, this); |
| 73 | + |
| 74 | + // include stack if exists and not turned off |
| 75 | + if (false !== stack && this.stack) { |
| 76 | + props.stack = this.stack; |
| 77 | + } |
| 78 | + |
| 79 | + return props; |
| 80 | + }; |
| 81 | +} |
0 commit comments