forked from nodejs/node-core-test
/
errors.js
397 lines (357 loc) · 10.9 KB
/
errors.js
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
// https://github.com/nodejs/node/blob/f8ce9117b19702487eb600493d941f7876e00e01/lib/internal/errors.js
'use strict'
const {
ArrayPrototypeFilter,
ArrayPrototypeJoin,
ArrayPrototypeUnshift,
Error,
ErrorCaptureStackTrace,
ObjectDefineProperty,
ObjectDefineProperties,
ObjectIsExtensible,
ObjectGetOwnPropertyDescriptor,
ObjectPrototypeHasOwnProperty,
ReflectApply,
SafeMap,
SafeWeakMap,
StringPrototypeIncludes,
StringPrototypeMatch,
StringPrototypeStartsWith,
StringPrototypeSlice,
Symbol,
SymbolFor
} = require('#internal/per_context/primordials')
const kIsNodeError = Symbol('kIsNodeError')
const messages = new SafeMap()
const codes = {}
const overrideStackTrace = new SafeWeakMap()
let userStackTraceLimit
const nodeInternalPrefix = '__node_internal_'
// Lazily loaded
let assert
let internalUtilInspect = null
function lazyInternalUtilInspect () {
if (!internalUtilInspect) {
internalUtilInspect = require('#internal/util/inspect')
}
return internalUtilInspect
}
let buffer
function lazyBuffer () {
if (buffer === undefined) { buffer = require('buffer').Buffer }
return buffer
}
function isErrorStackTraceLimitWritable () {
const desc = ObjectGetOwnPropertyDescriptor(Error, 'stackTraceLimit')
if (desc === undefined) {
return ObjectIsExtensible(Error)
}
return ObjectPrototypeHasOwnProperty(desc, 'writable')
? desc.writable
: desc.set !== undefined
}
function inspectWithNoCustomRetry (obj, options) {
const utilInspect = lazyInternalUtilInspect()
try {
return utilInspect.inspect(obj, options)
} catch {
return utilInspect.inspect(obj, { ...options, customInspect: false })
}
}
// A specialized Error that includes an additional info property with
// additional information about the error condition.
// It has the properties present in a UVException but with a custom error
// message followed by the uv error code and uv error message.
// It also has its own error code with the original uv error context put into
// `err.info`.
// The context passed into this error must have .code, .syscall and .message,
// and may have .path and .dest.
class SystemError extends Error {
constructor (key, context) {
const limit = Error.stackTraceLimit
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0
super()
// Reset the limit and setting the name property.
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit
const prefix = getMessage(key, [], this)
let message = `${prefix}: ${context.syscall} returned ` +
`${context.code} (${context.message})`
if (context.path !== undefined) { message += ` ${context.path}` }
if (context.dest !== undefined) { message += ` => ${context.dest}` }
captureLargerStackTrace(this)
this.code = key
ObjectDefineProperties(this, {
[kIsNodeError]: {
value: true,
enumerable: false,
writable: false,
configurable: true
},
name: {
value: 'SystemError',
enumerable: false,
writable: true,
configurable: true
},
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
info: {
value: context,
enumerable: true,
configurable: true,
writable: false
},
errno: {
get () {
return context.errno
},
set: (value) => {
context.errno = value
},
enumerable: true,
configurable: true
},
syscall: {
get () {
return context.syscall
},
set: (value) => {
context.syscall = value
},
enumerable: true,
configurable: true
}
})
if (context.path !== undefined) {
// TODO(BridgeAR): Investigate why and when the `.toString()` was
// introduced. The `path` and `dest` properties in the context seem to
// always be of type string. We should probably just remove the
// `.toString()` and `Buffer.from()` operations and set the value on the
// context as the user did.
ObjectDefineProperty(this, 'path', {
get () {
return context.path != null
? context.path.toString()
: context.path
},
set: (value) => {
context.path = value
? lazyBuffer().from(value.toString())
: undefined
},
enumerable: true,
configurable: true
})
}
if (context.dest !== undefined) {
ObjectDefineProperty(this, 'dest', {
get () {
return context.dest != null
? context.dest.toString()
: context.dest
},
set: (value) => {
context.dest = value
? lazyBuffer().from(value.toString())
: undefined
},
enumerable: true,
configurable: true
})
}
}
toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
[SymbolFor('nodejs.util.inspect.custom')] (recurseTimes, ctx) {
return lazyInternalUtilInspect().inspect(this, {
...ctx,
getters: true,
customInspect: false
})
}
}
function makeSystemErrorWithCode (key) {
return class NodeError extends SystemError {
constructor (ctx) {
super(key, ctx)
}
}
}
function makeNodeErrorWithCode (Base, key) {
return function NodeError (...args) {
const limit = Error.stackTraceLimit
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0
const error = new Base()
// Reset the limit and setting the name property.
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit
const message = getMessage(key, args, error)
ObjectDefineProperties(error, {
[kIsNodeError]: {
value: true,
enumerable: false,
writable: false,
configurable: true
},
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
value () {
return `${this.name} [${key}]: ${this.message}`
},
enumerable: false,
writable: true,
configurable: true
}
})
captureLargerStackTrace(error)
error.code = key
return error
}
}
/**
* This function removes unnecessary frames from Node.js core errors.
* @template {(...args: any[]) => any} T
* @type {(fn: T) => T}
*/
function hideStackFrames (fn) {
// We rename the functions that will be hidden to cut off the stacktrace
// at the outermost one
const hidden = nodeInternalPrefix + fn.name
ObjectDefineProperty(fn, 'name', { value: hidden })
return fn
}
// Utility function for registering the error codes. Only used here. Exported
// *only* to allow for testing.
function E (sym, val, def, ...otherClasses) {
// Special case for SystemError that formats the error message differently
// The SystemErrors only have SystemError as their base classes.
messages.set(sym, val)
if (def === SystemError) {
def = makeSystemErrorWithCode(sym)
} else {
def = makeNodeErrorWithCode(def, sym)
}
if (otherClasses.length !== 0) {
otherClasses.forEach((clazz) => {
def[clazz.name] = makeNodeErrorWithCode(clazz, sym)
})
}
codes[sym] = def
}
function getMessage (key, args, self) {
const msg = messages.get(key)
if (assert === undefined) assert = require('#internal/assert')
if (typeof msg === 'function') {
assert(
msg.length <= args.length, // Default options do not count.
`Code: ${key}; The provided arguments length (${args.length}) does not ` +
`match the required ones (${msg.length}).`
)
return ReflectApply(msg, self, args)
}
const expectedLength =
(StringPrototypeMatch(msg, /%[dfijoOs]/g) || []).length
assert(
expectedLength === args.length,
`Code: ${key}; The provided arguments length (${args.length}) does not ` +
`match the required ones (${expectedLength}).`
)
if (args.length === 0) { return msg }
ArrayPrototypeUnshift(args, msg)
return ReflectApply(lazyInternalUtilInspect().format, null, args)
}
const captureLargerStackTrace = hideStackFrames(
function captureLargerStackTrace (err) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable()
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = Infinity
}
ErrorCaptureStackTrace(err)
// Reset the limit
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit
return err
})
// Hide stack lines before the first user code line.
function hideInternalStackFrames (error) {
overrideStackTrace.set(error, (error, stackFrames) => {
let frames = stackFrames
if (typeof stackFrames === 'object') {
frames = ArrayPrototypeFilter(
stackFrames,
(frm) => !StringPrototypeStartsWith(frm.getFileName() || '',
'node:internal')
)
}
ArrayPrototypeUnshift(frames, error)
return ArrayPrototypeJoin(frames, '\n at ')
})
}
class AbortError extends Error {
constructor (message = 'The operation was aborted', options = undefined) {
super(message, options)
this.code = 'ABORT_ERR'
this.name = 'AbortError'
}
}
module.exports = {
AbortError,
codes,
inspectWithNoCustomRetry,
kIsNodeError
}
E('ERR_TAP_LEXER_ERROR', function (errorMsg) {
hideInternalStackFrames(this)
return errorMsg
}, Error)
E('ERR_TAP_PARSER_ERROR', function (errorMsg, details, tokenCausedError, source) {
hideInternalStackFrames(this)
this.cause = tokenCausedError
const { column, line, start, end } = tokenCausedError.location
const errorDetails = `${details} at line ${line}, column ${column} (start ${start}, end ${end})`
return errorMsg + errorDetails
}, SyntaxError)
E('ERR_TAP_VALIDATION_ERROR', function (errorMsg) {
hideInternalStackFrames(this)
return errorMsg
}, Error)
E('ERR_TEST_FAILURE', function (error, failureType) {
hideInternalStackFrames(this)
assert(typeof failureType === 'string',
"The 'failureType' argument must be of type string.")
let msg = error?.message ?? error
if (typeof msg !== 'string') {
msg = inspectWithNoCustomRetry(msg)
}
this.failureType = failureType
this.cause = error
return msg
}, Error)
E('ERR_INVALID_ARG_TYPE',
(name, expected, actual) => `Expected ${name} to be ${expected}, got type ${typeof actual}`,
TypeError)
E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
let inspected
try {
inspected = String(value)
} catch {
inspected = `type ${typeof value}`
}
if (inspected.length > 128) {
inspected = `${StringPrototypeSlice(inspected, 0, 128)}...`
}
const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument'
return `The ${type} '${name}' ${reason}. Received ${inspected}`
}, TypeError, RangeError)
E('ERR_OUT_OF_RANGE',
(name, expected, actual) => `Expected ${name} to be ${expected}, got ${actual}`,
RangeError)