-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.js
More file actions
507 lines (448 loc) · 10.7 KB
/
index.js
File metadata and controls
507 lines (448 loc) · 10.7 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
'use strict'
const assert = require('assert')
/** @typedef {{
type?: string;
errno?: string;
syscall?: string;
cause?(): Error;
fullType?(this: CustomError): string;
info?(): Record<string, unknown>;
toJSON?(): Record<string, unknown>;
} & Error} CustomError
*/
const nargs = /\{([0-9a-zA-Z_]+)\}/g
const lowerCaseKebabRegex = /([a-z])([0-9A-Z])/g
const upperCaseKebabRegex = /([A-Z])([A-Z])(?=[a-z])/g
const PLAIN_ERROR_FIELDS = [
'code',
'errno',
'syscall',
'status',
'statusCode',
'time',
'hostname',
'region',
'requestId',
'retryable',
'description',
'path',
'actual',
'expected',
'operator'
]
const EMPTY_OBJECT = {}
/** @type {Map<string, string>} */
const typeNameCache = new Map()
/** @type {(o: object, k: string) => unknown} */
const reflectGet = Reflect.get
class StructuredError extends Error {
/**
* @param {string} message
* @param {object} info
*/
constructor (message, info) {
super(message)
assert(typeof message === 'string')
assert(info !== null && typeof info === 'object')
/** @type {string} */
this.name = this.constructor.name
/** @type {string} */
this.type = getTypeNameCached(this.name)
/** @type {object} */
this.__info = info
}
/** @returns {Record<string, unknown>} */
info () {
return { ...this.__info }
}
/** @returns {Record<string, unknown>} */
toJSON () {
return {
...this.__info,
message: this.message,
stack: this.stack,
type: this.type,
name: this.name
}
}
/** @returns {string} */
static get type () {
return getTypeNameCached(this.name)
}
/**
* @param {CustomError | null} error
* @returns {Record<string, unknown>}
*/
static getInfo (error) {
if (!error) return {}
if (typeof error.info !== 'function') {
return { ...error }
}
return error.info()
}
/**
* @param {string} messageTmpl
* @param {Record<string, unknown>} [info]
* @returns {StructuredError}
*/
static create (messageTmpl, info) {
assert(typeof messageTmpl === 'string')
const msg = stringTemplate(messageTmpl, info)
return new this(msg, info || EMPTY_OBJECT)
}
}
exports.SError = StructuredError
class WrappedError extends Error {
/**
* @param {string} message
* @param {CustomError} cause
* @param {object} info
*/
constructor (message, cause, info) {
super(message)
assert(typeof message === 'string')
assert(info !== null && typeof info === 'object')
assert(isError(cause))
/** @type {string} */
this.name = this.constructor.name
/** @type {string} */
this.type = getTypeNameCached(this.name)
/** @type {object} */
this.__info = info
/** @type {CustomError} */
this.__cause = cause
}
/** @returns {string} */
fullType () {
/** @type {string} */
let causeType
if (typeof this.__cause.fullType === 'function') {
causeType = this.__cause.fullType()
} else if (this.__cause.type) {
causeType = this.__cause.type
} else if (this.__cause.errno || this.__cause.syscall) {
causeType = 'error.wrapped-io.' +
(this.__cause.syscall || 'unknown') + '.' +
(this.__cause.errno || '')
} else {
causeType = 'error.wrapped-unknown'
}
return this.type + '~!~' + causeType
}
/** @returns {CustomError} */
cause () {
return this.__cause
}
/** @returns {Record<string, unknown>} */
info () {
return WrappedError.fullInfo(this.cause(), this.__info)
}
/** @returns {Record<string, unknown>} */
toJSON () {
/** @type {Record<string, unknown>} */
let causeJSON
if (typeof this.__cause.toJSON === 'function') {
causeJSON = this.__cause.toJSON()
} else {
causeJSON = getJSONForPlainError(this.__cause)
}
if (causeJSON.stack) {
delete causeJSON.stack
}
return {
...this.info(),
message: this.message,
stack: this.stack,
type: this.type,
fullType: this.fullType(),
name: this.name,
cause: causeJSON
}
}
/** @returns {string} */
static get type () {
return getTypeNameCached(this.name)
}
/**
* @param {Error} err
* @returns {string}
*/
static fullStack (err) {
return fullStack(err)
}
/**
* @param {Error} err
* @param {string} name
* @returns {CustomError | null}
*/
static findCauseByName (err, name) {
return findCauseByName(err, name)
}
/**
* @param {CustomError | null} cause
* @param {object} [info]
* @returns {Record<string, unknown>}
*/
static fullInfo (cause, info) {
/** @type {Record<string, unknown> | undefined} */
let existing
if (cause && typeof cause.info === 'function') {
existing = cause.info()
} else if (cause) {
existing = getInfoForPlainError(cause)
}
if (existing) {
return { ...existing, ...info }
}
return { ...info }
}
/**
* @param {string} messageTmpl
* @param {Error} cause
* @param {object} [info]
* @returns {WrappedError}
*/
static wrap (messageTmpl, cause, info) {
assert(typeof messageTmpl === 'string')
assert(isError(cause))
let msg = stringTemplate(
messageTmpl,
WrappedError.fullInfo(cause, info)
)
if (!info || !reflectGet(info, 'skipCauseMessage')) {
msg = msg + ': ' + cause.message
}
return new this(msg, cause, info || EMPTY_OBJECT)
}
}
exports.WError = WrappedError
class MultiError extends Error {
/**
* @param {CustomError[]} errors
*/
constructor (errors) {
assert(Array.isArray(errors))
assert(errors.length >= 1)
for (const err of errors) {
assert(isError(err))
}
let msg = 'First of ' + String(errors.length)
msg += ' error' + (errors.length > 1 ? 's' : '')
msg += ': ' + errors[0].message
super(msg)
/** @type {CustomError[]} */
this.__errors = errors
/** @type {string} */
this.name = this.constructor.name
/** @type {string} */
this.type = createTypeStr(this.name) + '--' +
getTypeNameCached(errors[0].name)
}
/** @returns {CustomError[]} */
errors () {
return this.__errors.slice()
}
/**
* @returns {{
* message: string,
* stack: string,
* type: string,
* name: string,
* errors: object[]
* }}
*/
toJSON () {
/** @type {object[]} */
const out = []
for (const e of this.__errors) {
if (typeof e.toJSON === 'function') {
const nestedJSON = e.toJSON()
if (nestedJSON.stack) {
delete nestedJSON.stack
}
out.push(nestedJSON)
} else {
out.push(getJSONForPlainError(e))
}
}
return {
message: this.message,
stack: this.stack || '',
type: this.type,
name: this.name,
errors: out
}
}
/**
* @param {Error[]} errors
* @returns {null | Error | MultiError}
*/
static errorFromList (errors) {
assert(Array.isArray(errors))
if (errors.length === 0) {
return null
}
if (errors.length === 1) {
assert(isError(errors[0]))
return errors[0]
}
return new this(errors)
}
}
exports.MultiError = MultiError
/**
* @param {CustomError} err
* @param {string} name
* @returns {CustomError | null}
*/
function findCauseByName (err, name) {
assert(isError(err))
assert(typeof name === 'string')
assert(name.length > 0)
/** @type {CustomError | null} */
let currentErr = err
while (currentErr) {
if (currentErr.name === name) {
return currentErr
}
currentErr = typeof currentErr.cause === 'function'
? currentErr.cause() : null
}
return null
}
exports.findCauseByName = findCauseByName
/**
* @param {CustomError} err
* @returns {string}
*/
function fullStack (err) {
assert(isError(err))
const stack = err.stack || ''
if (typeof err.cause === 'function') {
return stack + '\nCaused by: ' + fullStack(err.cause())
}
return stack || ''
}
exports.fullStack = fullStack
/**
* @param {CustomError | null} error
* @returns {Record<string, unknown>}
*/
function getInfo (error) {
return StructuredError.getInfo(error)
}
exports.getInfo = getInfo
/**
* @param {string} messageTmpl
* @param {Error} cause
* @param {object} info
* @returns {WrappedError}
*/
function wrapf (messageTmpl, cause, info) {
return WrappedError.wrap(messageTmpl, cause, info)
}
exports.wrapf = wrapf
/**
* @param {string} messageTmpl
* @param {Record<string, unknown>} [info]
* @returns {StructuredError}
*/
function errorf (messageTmpl, info) {
return StructuredError.create(messageTmpl, info)
}
exports.errorf = errorf
/**
* @param {string} name
* @returns {string}
*/
function getTypeNameCached (name) {
let type = typeNameCache.get(name)
if (type) {
return type
}
type = createTypeStr(name)
typeNameCache.set(name, type)
return type
}
exports.getTypeName = getTypeNameCached
/**
* @param {string} name
* @returns {string}
*/
function createTypeStr (name) {
if (name === 'SError') {
return 'structured.error'
} else if (name === 'WError') {
return 'wrapped.error`'
}
return name
.replace(lowerCaseKebabRegex, '$1.$2')
.replace(upperCaseKebabRegex, '$1.$2')
.toLowerCase()
}
/**
* @param {CustomError} cause
* @returns {Record<string, unknown>}
*/
function getInfoForPlainError (cause) {
/** @type {Record<string, unknown>} */
const info = {}
for (const field of PLAIN_ERROR_FIELDS) {
const v = reflectGet(cause, field)
if (typeof v !== 'undefined') {
info[field] = v
}
}
return info
}
/**
* @param {Error} err
* @returns {boolean}
*/
function isError (err) {
return Object.prototype.toString.call(err) === '[object Error]'
? true
: err instanceof Error
}
/**
* @param {Error} err
* @returns {Record<string, unknown>}
*/
function getJSONForPlainError (err) {
const obj = getInfoForPlainError(err)
Object.assign(obj, {
message: err.message,
type: getTypeNameCached(err.name),
name: err.name
})
return obj
}
/**
* Taken from https://www.npmjs.com/package/string-template.
* source: https://github.com/Matt-Esch/string-template
*/
/**
* @param {string} string
* @param {Record<string, unknown>} [object]
* @returns {string}
*/
function stringTemplate (string, object) {
if (!object) return string
return string.replace(nargs, function replaceArg (
/** @type {string} */ match,
/** @type {string} */ word,
/** @type {number} */ index
) {
if (string[index - 1] === '{' &&
string[index + match.length] === '}'
) {
return word
} else {
const result = word in object ? object[word] : null
if (result === null || result === undefined) {
return ''
}
return String(result)
}
})
}