yerror 6.2.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
1
  /* eslint max-nested-callbacks:[0], no-magic-numbers:[0] */
2
+ import { describe, test } from '@jest/globals';
2
3
  import assert from 'assert';
3
- import YError from '.';
4
+ import { YError } from './index.js';
4
5
 
5
6
  describe('YError', () => {
6
7
  describe('.__constructor', () => {
7
- it('Should work', () => {
8
- var err = new YError('E_ERROR', 'arg1', 'arg2');
8
+ test('Should work', () => {
9
+ const err = new YError('E_ERROR', 'arg1', 'arg2');
9
10
 
10
11
  assert(err instanceof Error);
11
12
  assert.equal(err.name, err.toString());
@@ -13,16 +14,16 @@ describe('YError', () => {
13
14
  assert.deepEqual(err.params, ['arg1', 'arg2']);
14
15
  assert.equal(err.toString(), 'YError: E_ERROR (arg1, arg2)');
15
16
  });
16
- it('Should work without code', () => {
17
- var err = new YError();
17
+ test('Should work without code', () => {
18
+ const err = new YError();
18
19
 
19
20
  assert.equal(err.code, 'E_UNEXPECTED');
20
21
  assert.deepEqual(err.params, []);
21
22
  assert.equal(err.toString(), 'YError: E_UNEXPECTED ()');
22
23
  assert.equal(err.name, err.toString());
23
24
  });
24
- it('Should work without new', () => {
25
- var err = new YError('E_ERROR', 'arg1', 'arg2');
25
+ test('Should work without new', () => {
26
+ const err = new YError('E_ERROR', 'arg1', 'arg2');
26
27
 
27
28
  assert.equal(err.code, 'E_ERROR');
28
29
  assert(err instanceof YError);
@@ -33,69 +34,77 @@ describe('YError', () => {
33
34
  });
34
35
 
35
36
  describe('.wrap()', () => {
36
- it('Should work with standard errors and a message', () => {
37
+ test('Should work with standard errors and a message', () => {
37
38
  // eslint-disable-line
38
- var err = YError.wrap(new Error('This is an error!'));
39
+ const err = YError.wrap(new Error('This is an error!'));
39
40
 
40
41
  assert.equal(err.code, 'E_UNEXPECTED');
41
42
  assert.equal(err.wrappedErrors.length, 1);
42
43
  assert.deepEqual(err.params, ['This is an error!']);
43
44
 
44
- if (Error.captureStackTrace) {
45
+ if ('captureStackTrace' in Error) {
45
46
  assert(
46
- -1 !== err.stack.indexOf('Error: This is an error!'),
47
+ -1 !== (err.stack || '').indexOf('Error: This is an error!'),
47
48
  'Stack contains original error.',
48
49
  );
49
50
  assert(
50
- -1 !== err.stack.indexOf('YError: E_UNEXPECTED (This is an error!)'),
51
+ -1 !==
52
+ (err.stack || '').indexOf(
53
+ 'YError: E_UNEXPECTED (This is an error!)',
54
+ ),
51
55
  'Stack contains cast error.',
52
56
  );
53
57
  assert.equal(err.name, err.toString());
54
58
  }
55
59
  });
56
60
 
57
- it('Should work with standard errors and an error code', () => {
58
- var err = YError.wrap(new Error('E_ERROR'));
61
+ test('Should work with standard errors and an error code', () => {
62
+ const err = YError.wrap(new Error('E_ERROR'));
59
63
 
60
64
  assert.equal(err.code, 'E_ERROR');
61
65
  assert.equal(err.wrappedErrors.length, 1);
62
66
  assert.deepEqual(err.params, []);
63
67
 
64
- if (Error.captureStackTrace) {
68
+ if ('captureStackTrace' in Error) {
65
69
  assert(
66
- -1 !== err.stack.indexOf('Error: E_ERROR'),
70
+ -1 !== (err.stack || '').indexOf('Error: E_ERROR'),
67
71
  'Stack contains original error.',
68
72
  );
69
73
  assert(
70
- -1 !== err.stack.indexOf('YError: E_ERROR ()'),
74
+ -1 !== (err.stack || '').indexOf('YError: E_ERROR ()'),
71
75
  'Stack contains cast error.',
72
76
  );
73
77
  }
74
78
  assert.equal(err.name, err.toString());
75
79
  });
76
80
 
77
- it('Should work with standard errors, an error code and params', () => {
78
- var err = YError.wrap(new Error('E_ERROR'), 'E_ERROR_2', 'arg1', 'arg2');
81
+ test('Should work with standard errors, an error code and params', () => {
82
+ const err = YError.wrap(
83
+ new Error('E_ERROR'),
84
+ 'E_ERROR_2',
85
+ 'arg1',
86
+ 'arg2',
87
+ );
79
88
 
80
89
  assert.equal(err.code, 'E_ERROR_2');
81
90
  assert.equal(err.wrappedErrors.length, 1);
82
91
  assert.deepEqual(err.params, ['arg1', 'arg2']);
83
92
 
84
- if (Error.captureStackTrace) {
93
+ if ('captureStackTrace' in Error) {
85
94
  assert(
86
- -1 !== err.stack.indexOf('Error: E_ERROR'),
95
+ -1 !== (err.stack || '').indexOf('Error: E_ERROR'),
87
96
  'Stack contains first error.',
88
97
  );
89
98
  assert(
90
- -1 !== err.stack.indexOf('YError: E_ERROR_2 (arg1, arg2)'),
99
+ -1 !== (err.stack || '').indexOf('YError: E_ERROR_2 (arg1, arg2)'),
91
100
  'Stack contains second error.',
92
101
  );
93
102
  }
94
103
  assert.equal(err.name, err.toString());
95
104
  });
96
105
 
97
- it('Should work with several wrapped errors', () => {
98
- var err = YError.wrap(
106
+ test('Should work with several wrapped errors', () => {
107
+ const err = YError.wrap(
99
108
  YError.wrap(new Error('E_ERROR_1'), 'E_ERROR_2', 'arg2.1', 'arg2.2'),
100
109
  'E_ERROR_3',
101
110
  'arg3.1',
@@ -106,17 +115,19 @@ describe('YError', () => {
106
115
  assert.equal(err.wrappedErrors.length, 2);
107
116
  assert.deepEqual(err.params, ['arg3.1', 'arg3.2']);
108
117
 
109
- if (Error.captureStackTrace) {
118
+ if ('captureStackTrace' in Error) {
110
119
  assert(
111
- -1 !== err.stack.indexOf('Error: E_ERROR_1'),
120
+ -1 !== (err.stack || '').indexOf('Error: E_ERROR_1'),
112
121
  'Stack contains first error.',
113
122
  );
114
123
  assert(
115
- -1 !== err.stack.indexOf('YError: E_ERROR_2 (arg2.1, arg2.2)'),
124
+ -1 !==
125
+ (err.stack || '').indexOf('YError: E_ERROR_2 (arg2.1, arg2.2)'),
116
126
  'Stack contains second error.',
117
127
  );
118
128
  assert(
119
- -1 !== err.stack.indexOf('YError: E_ERROR_3 (arg3.1, arg3.2)'),
129
+ -1 !==
130
+ (err.stack || '').indexOf('YError: E_ERROR_3 (arg3.1, arg3.2)'),
120
131
  'Stack contains second error.',
121
132
  );
122
133
  }
@@ -125,35 +136,38 @@ describe('YError', () => {
125
136
  });
126
137
 
127
138
  describe('.cast()', () => {
128
- it('Should work with standard errors and a message', () => {
129
- var err = YError.cast(new Error('This is an error!'));
139
+ test('Should work with standard errors and a message', () => {
140
+ const err = YError.cast(new Error('This is an error!'));
130
141
 
131
142
  assert.equal(err.code, 'E_UNEXPECTED');
132
143
  assert.equal(err.wrappedErrors.length, 1);
133
144
  assert.deepEqual(err.params, ['This is an error!']);
134
145
 
135
- if (Error.captureStackTrace) {
146
+ if ('captureStackTrace' in Error) {
136
147
  assert(
137
- -1 !== err.stack.indexOf('Error: This is an error!'),
148
+ -1 !== (err.stack || '').indexOf('Error: This is an error!'),
138
149
  'Stack contains original error.',
139
150
  );
140
151
  assert(
141
- -1 !== err.stack.indexOf('YError: E_UNEXPECTED (This is an error!)'),
152
+ -1 !==
153
+ (err.stack || '').indexOf(
154
+ 'YError: E_UNEXPECTED (This is an error!)',
155
+ ),
142
156
  'Stack contains cast error.',
143
157
  );
144
158
  }
145
159
  assert.equal(err.name, err.toString());
146
160
  });
147
161
 
148
- it('Should let YError instances pass through', () => {
149
- var err = YError.cast(new YError('E_ERROR', 'arg1', 'arg2'));
162
+ test('Should let YError instances pass through', () => {
163
+ const err = YError.cast(new YError('E_ERROR', 'arg1', 'arg2'));
150
164
 
151
165
  assert.equal(err.code, 'E_ERROR');
152
166
  assert.deepEqual(err.params, ['arg1', 'arg2']);
153
167
 
154
- if (Error.captureStackTrace) {
168
+ if ('captureStackTrace' in Error) {
155
169
  assert(
156
- -1 !== err.stack.indexOf('YError: E_ERROR (arg1, arg2)'),
170
+ -1 !== (err.stack || '').indexOf('YError: E_ERROR (arg1, arg2)'),
157
171
  'Stack contains cast error.',
158
172
  );
159
173
  }
@@ -162,54 +176,59 @@ describe('YError', () => {
162
176
  });
163
177
 
164
178
  describe('.bump()', () => {
165
- it('Should work with standard errors and a message', () => {
166
- var err = YError.bump(new Error('This is an error!'));
179
+ test('Should work with standard errors and a message', () => {
180
+ const err = YError.bump(new Error('This is an error!'));
167
181
 
168
182
  assert.equal(err.code, 'E_UNEXPECTED');
169
183
  assert.equal(err.wrappedErrors.length, 1);
170
184
  assert.deepEqual(err.params, ['This is an error!']);
171
185
 
172
- if (Error.captureStackTrace) {
186
+ if ('captureStackTrace' in Error) {
173
187
  assert(
174
- -1 !== err.stack.indexOf('Error: This is an error!'),
188
+ -1 !== (err.stack || '').indexOf('Error: This is an error!'),
175
189
  'Stack contains original error.',
176
190
  );
177
191
  assert(
178
- -1 !== err.stack.indexOf('YError: E_UNEXPECTED (This is an error!)'),
192
+ -1 !==
193
+ (err.stack || '').indexOf(
194
+ 'YError: E_UNEXPECTED (This is an error!)',
195
+ ),
179
196
  'Stack contains bumped error.',
180
197
  );
181
198
  }
182
199
  assert.equal(err.name, err.toString());
183
200
  });
184
201
 
185
- it('Should work with YError like errors', () => {
186
- var baseErr = new Error('E_A_NEW_ERROR');
202
+ test('Should work with YError like errors', () => {
203
+ const baseErr = new Error('E_A_NEW_ERROR');
187
204
 
188
- baseErr.code = 'E_A_NEW_ERROR';
189
- baseErr.params = ['baseParam1', 'baseParam2'];
205
+ (baseErr as YError).code = 'E_A_NEW_ERROR';
206
+ (baseErr as YError).params = ['baseParam1', 'baseParam2'];
190
207
 
191
- let err = YError.bump(baseErr);
208
+ const err = YError.bump(baseErr);
192
209
 
193
210
  assert.equal(err.code, 'E_A_NEW_ERROR');
194
211
  assert.equal(err.wrappedErrors.length, 1);
195
212
  assert.deepEqual(err.params, ['baseParam1', 'baseParam2']);
196
213
 
197
- if (Error.captureStackTrace) {
214
+ if ('captureStackTrace' in Error) {
198
215
  assert(
199
- -1 !== err.stack.indexOf('Error: E_A_NEW_ERROR'),
216
+ -1 !== (err.stack || '').indexOf('Error: E_A_NEW_ERROR'),
200
217
  'Stack contains original error.',
201
218
  );
202
219
  assert(
203
220
  -1 !==
204
- err.stack.indexOf('YError: E_A_NEW_ERROR (baseParam1, baseParam2)'),
221
+ (err.stack || '').indexOf(
222
+ 'YError: E_A_NEW_ERROR (baseParam1, baseParam2)',
223
+ ),
205
224
  'Stack contains bumped error.',
206
225
  );
207
226
  }
208
227
  assert.equal(err.name, err.toString());
209
228
  });
210
229
 
211
- it('Should work with Y errors and a message', () => {
212
- var err = YError.bump(
230
+ test('Should work with Y errors and a message', () => {
231
+ const err = YError.bump(
213
232
  new YError('E_ERROR', 'arg1.1', 'arg1.2'),
214
233
  'E_ERROR_2',
215
234
  'arg2.1',
@@ -219,13 +238,13 @@ describe('YError', () => {
219
238
  assert.equal(err.code, 'E_ERROR');
220
239
  assert.deepEqual(err.params, ['arg1.1', 'arg1.2']);
221
240
 
222
- if (Error.captureStackTrace) {
241
+ if ('captureStackTrace' in Error) {
223
242
  assert(
224
- -1 !== err.stack.indexOf('YError: E_ERROR (arg1.1, arg1.2)'),
243
+ -1 !== (err.stack || '').indexOf('YError: E_ERROR (arg1.1, arg1.2)'),
225
244
  'Stack contains original error.',
226
245
  );
227
246
  assert(
228
- -1 !== err.stack.indexOf('YError: E_ERROR (arg1.1, arg1.2)'),
247
+ -1 !== (err.stack || '').indexOf('YError: E_ERROR (arg1.1, arg1.2)'),
229
248
  'Stack contains bumped error.',
230
249
  );
231
250
  }
package/src/index.ts ADDED
@@ -0,0 +1,192 @@
1
+ import os from 'os';
2
+
3
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
+ type YErrorParams = any;
5
+
6
+ /**
7
+ * A YError class able to contain some params and
8
+ * print better stack traces
9
+ * @extends Error
10
+ */
11
+ class YError extends Error {
12
+ code: string;
13
+ params: YErrorParams[];
14
+ wrappedErrors: (Error | YError)[];
15
+ /**
16
+ * Creates a new YError with an error code
17
+ * and some params as debug values.
18
+ * @param {string} [errorCode = 'E_UNEXPECTED']
19
+ * The error code corresponding to the actual error
20
+ * @param {...YErrorParams} [params]
21
+ * Some additional debugging values
22
+ */
23
+ constructor(errorCode: string, ...params: YErrorParams[]);
24
+ constructor(
25
+ wrappedErrors?: Error[],
26
+ errorCode?: string,
27
+ ...params: YErrorParams[]
28
+ );
29
+ constructor(wrappedErrors, errorCode, ...params) {
30
+ // Detecting if wrappedErrors are passed
31
+ if (!(wrappedErrors instanceof Array)) {
32
+ params = ('undefined' === typeof errorCode ? [] : [errorCode]).concat(
33
+ params,
34
+ );
35
+ errorCode = wrappedErrors;
36
+ wrappedErrors = [];
37
+ }
38
+
39
+ // Call the parent constructor
40
+ super(errorCode);
41
+
42
+ // Filling error
43
+ this.code = errorCode || 'E_UNEXPECTED';
44
+ this.params = params;
45
+ this.wrappedErrors = wrappedErrors;
46
+ this.name = this.toString();
47
+
48
+ if (Error.captureStackTrace) {
49
+ Error.captureStackTrace(this, this.constructor);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Wraps any error and output a YError with an error
55
+ * code and some params as debug values.
56
+ * @param {Error} err
57
+ * The error to wrap
58
+ * @param {string} [errorCode = 'E_UNEXPECTED']
59
+ * The error code corresponding to the actual error
60
+ * @param {...YErrorParams} [params]
61
+ * Some additional debugging values
62
+ * @return {YError}
63
+ * The wrapped error
64
+ */
65
+ static wrap<E extends Error | YError>(
66
+ err: E,
67
+ errorCode?: string,
68
+ ...params: YErrorParams[]
69
+ ): YError {
70
+ const wrappedErrorIsACode = _looksLikeAYErrorCode(err.message);
71
+ const wrappedErrors = (
72
+ 'wrappedErrors' in err ? err.wrappedErrors : []
73
+ ).concat(err);
74
+
75
+ if (!errorCode) {
76
+ if (wrappedErrorIsACode) {
77
+ errorCode = err.message;
78
+ } else {
79
+ errorCode = 'E_UNEXPECTED';
80
+ }
81
+ }
82
+ if (err.message && !wrappedErrorIsACode) {
83
+ params.push(err.message);
84
+ }
85
+ return new YError(wrappedErrors, errorCode, ...params);
86
+ }
87
+
88
+ /**
89
+ * Return a YError as is or wraps any other error and output
90
+ * a YError with a code and some params as debug values.
91
+ * @param {Error} err
92
+ * The error to cast
93
+ * @param {string} [errorCode = 'E_UNEXPECTED']
94
+ * The error code corresponding to the actual error
95
+ * @param {...YErrorParams} [params]
96
+ * Some additional debugging values
97
+ * @return {YError}
98
+ * The wrapped error
99
+ */
100
+ static cast<E extends Error | YError>(
101
+ err: E,
102
+ errorCode?: string,
103
+ ...params: YErrorParams[]
104
+ ): YError {
105
+ if (_looksLikeAYError(err)) {
106
+ return err as unknown as YError;
107
+ }
108
+ return YError.wrap(err, errorCode, ...params);
109
+ }
110
+
111
+ /**
112
+ * Same than `YError.wrap()` but preserves the code
113
+ * and the debug values of the error if it is
114
+ * already an instance of the YError constructor.
115
+ * @param {Error} err
116
+ * The error to bump
117
+ * @param {string} [errorCode = 'E_UNEXPECTED']
118
+ * The error code corresponding to the actual error
119
+ * @param {...YErrorParams} [params]
120
+ * Some additional debugging values
121
+ * @return {YError}
122
+ * The wrapped error
123
+ */
124
+ static bump<E extends Error | YError>(
125
+ err: E,
126
+ errorCode?: string,
127
+ ...params: YErrorParams[]
128
+ ): YError {
129
+ if (_looksLikeAYError(err)) {
130
+ return YError.wrap(err, (err as YError).code, ...(err as YError).params);
131
+ }
132
+ return YError.wrap(err, errorCode, ...params);
133
+ }
134
+
135
+ toString(): string {
136
+ return (
137
+ (this.wrappedErrors.length
138
+ ? // eslint-disable-next-line
139
+ this.wrappedErrors[this.wrappedErrors.length - 1].stack + os.EOL
140
+ : '') +
141
+ this.constructor.name +
142
+ ': ' +
143
+ this.code +
144
+ ' (' +
145
+ this.params.join(', ') +
146
+ ')'
147
+ );
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Allow to print a stack from anything (especially catched
153
+ * errors that may or may not contain errors 🤷).
154
+ * @param {Error} err
155
+ * The error to print
156
+ * @return {string}
157
+ * The stack trace if any
158
+ */
159
+ export function printStackTrace(err: Error | YError): string {
160
+ return typeof err === 'object' && typeof err.stack === 'string'
161
+ ? err.stack
162
+ : `[no_stack_trace]: error is ${
163
+ err != null && typeof err.toString === 'function'
164
+ ? err.toString()
165
+ : typeof err
166
+ }`;
167
+ }
168
+
169
+ // In order to keep compatibility through major versions
170
+ // we have to make kind of an cross major version instanceof
171
+ function _looksLikeAYError(err: Error | YError): boolean {
172
+ return (
173
+ !!(err instanceof YError) ||
174
+ !!(
175
+ err.constructor &&
176
+ err.constructor.name &&
177
+ err.constructor.name.endsWith('Error') &&
178
+ 'code' in err &&
179
+ 'string' === typeof err.code &&
180
+ _looksLikeAYErrorCode(err.code) &&
181
+ 'params' in err &&
182
+ err.params &&
183
+ err.params instanceof Array
184
+ )
185
+ );
186
+ }
187
+
188
+ function _looksLikeAYErrorCode(str: string): boolean {
189
+ return /^([A-Z0-9_]+)$/.test(str);
190
+ }
191
+
192
+ export { YError };
package/dist/index.mjs DELETED
@@ -1,117 +0,0 @@
1
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2
-
3
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
4
-
5
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
6
-
7
- function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
8
-
9
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
10
-
11
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
12
-
13
- function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
14
-
15
- function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
16
-
17
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
18
-
19
- function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
20
-
21
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
22
-
23
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
24
-
25
- import os from 'os';
26
-
27
- let YError = function (_Error) {
28
- _inherits(YError, _Error);
29
-
30
- function YError(wrappedErrors, errorCode, ...params) {
31
- var _this;
32
-
33
- _classCallCheck(this, YError);
34
-
35
- if (!(wrappedErrors instanceof Array)) {
36
- params = ('undefined' === typeof errorCode ? [] : [errorCode]).concat(params);
37
- errorCode = wrappedErrors;
38
- wrappedErrors = [];
39
- }
40
-
41
- _this = _possibleConstructorReturn(this, _getPrototypeOf(YError).call(this, errorCode));
42
- _this.code = errorCode || 'E_UNEXPECTED';
43
- _this.params = params;
44
- _this.wrappedErrors = wrappedErrors;
45
- _this.name = _this.toString();
46
-
47
- if (Error.captureStackTrace) {
48
- Error.captureStackTrace(_assertThisInitialized(_this), _this.constructor);
49
- }
50
-
51
- return _this;
52
- }
53
-
54
- _createClass(YError, [{
55
- key: "toString",
56
- value: function toString() {
57
- return (this.wrappedErrors.length ? this.wrappedErrors[this.wrappedErrors.length - 1].stack + os.EOL : '') + this.constructor.name + ': ' + this.code + ' (' + this.params.join(', ') + ')';
58
- }
59
- }]);
60
-
61
- return YError;
62
- }(_wrapNativeSuper(Error));
63
-
64
- YError.wrap = function yerrorWrap(err, errorCode, ...params) {
65
- let yError = null;
66
-
67
- const wrappedErrorIsACode = _looksLikeAYErrorCode(err.message);
68
-
69
- const wrappedErrors = (err.wrappedErrors || []).concat(err);
70
-
71
- if (!errorCode) {
72
- if (wrappedErrorIsACode) {
73
- errorCode = err.message;
74
- } else {
75
- errorCode = 'E_UNEXPECTED';
76
- }
77
- }
78
-
79
- if (err.message && !wrappedErrorIsACode) {
80
- params.push(err.message);
81
- }
82
-
83
- yError = new YError(wrappedErrors, errorCode, ...params);
84
- return yError;
85
- };
86
-
87
- YError.cast = function yerrorCast(err, ...params) {
88
- if (_looksLikeAYError(err)) {
89
- return err;
90
- }
91
-
92
- return YError.wrap.apply(YError, [err].concat(params));
93
- };
94
-
95
- YError.bump = function yerrorBump(err, ...params) {
96
- if (_looksLikeAYError(err)) {
97
- return YError.wrap.apply(YError, [err, err.code].concat(err.params));
98
- }
99
-
100
- return YError.wrap.apply(YError, [err].concat(params));
101
- };
102
-
103
- export function printStackTrace(err) {
104
- return typeof err === 'object' && typeof err.stack === 'function' ? err.stack() : `[no_stack_trace]: error is ${err != null && typeof err.toString === 'function' ? err.toString() : typeof err}`;
105
- }
106
-
107
- function _looksLikeAYError(err) {
108
- return err instanceof YError || err.constructor && err.constructor.name && err.constructor.name.endsWith('Error') && 'string' === typeof err.code && _looksLikeAYErrorCode(err.code) && err.params && err.params instanceof Array;
109
- }
110
-
111
- function _looksLikeAYErrorCode(str) {
112
- return /^([A-Z0-9_]+)$/.test(str);
113
- }
114
-
115
- export default YError;
116
- export { YError };
117
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["os","YError","wrappedErrors","errorCode","params","Array","concat","code","name","toString","Error","captureStackTrace","constructor","length","stack","EOL","join","wrap","yerrorWrap","err","yError","wrappedErrorIsACode","_looksLikeAYErrorCode","message","push","cast","yerrorCast","_looksLikeAYError","apply","bump","yerrorBump","printStackTrace","endsWith","str","test"],"sources":["../src/index.js"],"sourcesContent":["import os from 'os';\n\n/**\n * An YError class able to contain some params and\n * print better stack traces\n * @extends Error\n */\nclass YError extends Error {\n /**\n * Creates a new YError with an error code\n * and some params as debug values.\n * @param {string} [errorCode = 'E_UNEXPECTED']\n * The error code corresponding to the actual error\n * @param {...any} [params]\n * Some additional debugging values\n */\n constructor(wrappedErrors, errorCode, ...params) {\n // Detecting if wrappedErrors are passed\n if (!(wrappedErrors instanceof Array)) {\n params = ('undefined' === typeof errorCode ? [] : [errorCode]).concat(\n params,\n );\n errorCode = wrappedErrors;\n wrappedErrors = [];\n }\n\n // Call the parent constructor\n super(errorCode);\n\n // Filling error\n this.code = errorCode || 'E_UNEXPECTED';\n this.params = params;\n this.wrappedErrors = wrappedErrors;\n this.name = this.toString();\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n toString() {\n return (\n (this.wrappedErrors.length\n ? // eslint-disable-next-line\n this.wrappedErrors[this.wrappedErrors.length - 1].stack + os.EOL\n : '') +\n this.constructor.name +\n ': ' +\n this.code +\n ' (' +\n this.params.join(', ') +\n ')'\n );\n }\n}\n\n/**\n * Wraps any error and output a YError with an error\n * code and some params as debug values.\n * @param {Error} err\n * The error to wrap\n * @param {string} [errorCode = 'E_UNEXPECTED']\n * The error code corresponding to the actual error\n * @param {...any} [params]\n * Some additional debugging values\n * @return {YError}\n * The wrapped error\n */\nYError.wrap = function yerrorWrap(err, errorCode, ...params) {\n let yError = null;\n const wrappedErrorIsACode = _looksLikeAYErrorCode(err.message);\n const wrappedErrors = (err.wrappedErrors || []).concat(err);\n\n if (!errorCode) {\n if (wrappedErrorIsACode) {\n errorCode = err.message;\n } else {\n errorCode = 'E_UNEXPECTED';\n }\n }\n if (err.message && !wrappedErrorIsACode) {\n params.push(err.message);\n }\n yError = new YError(wrappedErrors, errorCode, ...params);\n return yError;\n};\n\n/**\n * Return a YError as is or wraps any other error and output\n * a YError with a code and some params as debug values.\n * @param {Error} err\n * The error to cast\n * @param {string} [errorCode = 'E_UNEXPECTED']\n * The error code corresponding to the actual error\n * @param {...any} [params]\n * Some additional debugging values\n * @return {YError}\n * The wrapped error\n */\nYError.cast = function yerrorCast(err, ...params) {\n if (_looksLikeAYError(err)) {\n return err;\n }\n return YError.wrap.apply(YError, [err].concat(params));\n};\n\n/**\n * Same than `YError.wrap()` but preserves the code\n * and the debug values of the error if it is\n * already an instance of the YError constructor.\n * @param {Error} err\n * The error to bump\n * @param {string} [errorCode = 'E_UNEXPECTED']\n * The error code corresponding to the actual error\n * @param {...any} [params]\n * Some additional debugging values\n * @return {YError}\n * The wrapped error\n */\nYError.bump = function yerrorBump(err, ...params) {\n if (_looksLikeAYError(err)) {\n return YError.wrap.apply(YError, [err, err.code].concat(err.params));\n }\n return YError.wrap.apply(YError, [err].concat(params));\n};\n\n/**\n * Allow to print a stack from anything (especially catched\n * errors that may or may not contain errors 🤷).\n * @param {Error} err\n * The error to print\n * @return {string}\n * The stack trace if any\n */\nexport function printStackTrace(err) {\n return typeof err === 'object' && typeof err.stack === 'function'\n ? err.stack()\n : `[no_stack_trace]: error is ${\n err != null && typeof err.toString === 'function'\n ? err.toString()\n : typeof err\n }`;\n}\n\n// In order to keep compatibility through major versions\n// we have to make kind of an cross major version instanceof\nfunction _looksLikeAYError(err) {\n return (\n err instanceof YError ||\n (err.constructor &&\n err.constructor.name &&\n err.constructor.name.endsWith('Error') &&\n 'string' === typeof err.code &&\n _looksLikeAYErrorCode(err.code) &&\n err.params &&\n err.params instanceof Array)\n );\n}\n\nfunction _looksLikeAYErrorCode(str) {\n return /^([A-Z0-9_]+)$/.test(str);\n}\n\nexport default YError;\nexport { YError };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,EAAP,MAAe,IAAf;;IAOMC,M;;;EASJ,gBAAYC,aAAZ,EAA2BC,SAA3B,EAAsC,GAAGC,MAAzC,EAAiD;IAAA;;IAAA;;IAE/C,IAAI,EAAEF,aAAa,YAAYG,KAA3B,CAAJ,EAAuC;MACrCD,MAAM,GAAG,CAAC,gBAAgB,OAAOD,SAAvB,GAAmC,EAAnC,GAAwC,CAACA,SAAD,CAAzC,EAAsDG,MAAtD,CACPF,MADO,CAAT;MAGAD,SAAS,GAAGD,aAAZ;MACAA,aAAa,GAAG,EAAhB;IACD;;IAGD,4EAAMC,SAAN;IAGA,MAAKI,IAAL,GAAYJ,SAAS,IAAI,cAAzB;IACA,MAAKC,MAAL,GAAcA,MAAd;IACA,MAAKF,aAAL,GAAqBA,aAArB;IACA,MAAKM,IAAL,GAAY,MAAKC,QAAL,EAAZ;;IAEA,IAAIC,KAAK,CAACC,iBAAV,EAA6B;MAC3BD,KAAK,CAACC,iBAAN,gCAA8B,MAAKC,WAAnC;IACD;;IArB8C;EAsBhD;;;;+BAEU;MACT,OACE,CAAC,KAAKV,aAAL,CAAmBW,MAAnB,GAEG,KAAKX,aAAL,CAAmB,KAAKA,aAAL,CAAmBW,MAAnB,GAA4B,CAA/C,EAAkDC,KAAlD,GAA0Dd,EAAE,CAACe,GAFhE,GAGG,EAHJ,IAIA,KAAKH,WAAL,CAAiBJ,IAJjB,GAKA,IALA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