-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy patherror_utils.ts
643 lines (498 loc) · 16.8 KB
/
error_utils.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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
// See: ./errorScenarios.md for details about error messages and stack traces
import chai from 'chai'
import _ from 'lodash'
import $dom from '../dom'
import { stripAnsi } from '@packages/errors'
import $errorMessages from './error_messages'
import $stackUtils, { StackAndCodeFrameIndex } from './stack_utils'
import $utils from './utils'
import type { HandlerType } from './runner'
const ERROR_PROPS = ['message', 'type', 'name', 'stack', 'parsedStack', 'fileName', 'lineNumber', 'columnNumber', 'host', 'uncaught', 'actual', 'expected', 'showDiff', 'isPending', 'isRecovered', 'docsUrl', 'codeFrame'] as const
const ERR_PREPARED_FOR_SERIALIZATION = Symbol('ERR_PREPARED_FOR_SERIALIZATION')
const crossOriginScriptRe = /^script error/i
if (!Error.captureStackTrace) {
Error.captureStackTrace = (err, fn) => {
const stack = (new Error()).stack;
(err as Error).stack = $stackUtils.stackWithLinesDroppedFromMarker(stack, fn?.name)
}
}
const prepareErrorForSerialization = (err) => {
if (typeof err === 'string') {
err = new Error(err)
}
if (err[ERR_PREPARED_FOR_SERIALIZATION]) {
return err
}
if (err.type === 'existence' || $dom.isDom(err.actual) || $dom.isDom(err.expected)) {
err.showDiff = false
}
if (err.showDiff === true) {
if (err.actual) {
err.actual = chai.util.inspect(err.actual)
}
if (err.expected) {
err.expected = chai.util.inspect(err.expected)
}
} else {
delete err.actual
delete err.expected
delete err.showDiff
}
err[ERR_PREPARED_FOR_SERIALIZATION] = true
return err
}
// some errors, probably from user callbacks, might be boolean, number or falsy values
// which means serializing will not provide any useful context
const isSerializableError = (err) => {
return !!err && (typeof err === 'object' || typeof err === 'string')
}
const wrapErr = (err) => {
if (!isSerializableError(err)) return
prepareErrorForSerialization(err)
return $utils.reduceProps(err, ERROR_PROPS)
}
const isAssertionErr = (err: Error) => {
return err.name === 'AssertionError'
}
const isChaiValidationErr = (err: Error) => {
return _.startsWith(err.message, 'Invalid Chai property')
}
const isCypressErr = (err: Error): boolean => {
return err.name === 'CypressError'
}
const isSpecError = (spec, err) => {
return _.includes(err.stack, spec.relative)
}
const mergeErrProps = (origErr: Error, ...newProps): Error => {
return _.extend(origErr, ...newProps)
}
const stackWithReplacedProps = (err, props) => {
const {
message: originalMessage,
name: originalName,
stack: originalStack,
} = err
const {
message: newMessage,
name: newName,
} = props
// if stack doesn't already exist, leave it as is
if (!originalStack) return originalStack
let stack
if (newMessage) {
stack = originalStack.replace(originalMessage, newMessage)
}
if (newName) {
stack = originalStack.replace(originalName, newName)
}
if (originalMessage) {
return stack
}
// if message is undefined or an empty string, the error (in Chrome at least)
// is 'Error\n\n<stack>' and it results in wrongly prepending the
// new message, looking like '<newMsg>Error\n\n<stack>'
const message = newMessage || err.message
const name = newName || err.name
return originalStack.replace(originalName, `${name}: ${message}`)
}
const getUserInvocationStack = (err, state) => {
const current = state('current')
const currentAssertionCommand = current?.get('currentAssertionCommand')
const withInvocationStack = currentAssertionCommand || current
// user assertion errors (expect().to, etc) get their invocation stack
// attached to the error thrown from chai
// command errors and command assertion errors (default assertion or cy.should)
// have the invocation stack attached to the current command
// prefer err.userInvocation stack if it's been set
let userInvocationStack = getUserInvocationStackFromError(err) || state('currentAssertionUserInvocationStack')
// if there is no user invocation stack from an assertion or it is the default
// assertion, meaning it came from a command (e.g. cy.get), prefer the
// command's user invocation stack so the code frame points to the command.
// `should` callbacks are tricky because the `currentAssertionUserInvocationStack`
// points to the `cy.should`, but the error came from inside the callback,
// so we need to prefer that.
if (
!userInvocationStack
|| err.isDefaultAssertionErr
|| (currentAssertionCommand && !current?.get('followedByShouldCallback'))
|| withInvocationStack?.get('selector')
) {
userInvocationStack = withInvocationStack?.get('userInvocationStack')
}
if (!userInvocationStack) return
if (
isCypressErr(err)
|| isAssertionErr(err)
|| isChaiValidationErr(err)
) {
return userInvocationStack
}
}
const modifyErrMsg = (err, newErrMsg, cb) => {
err.stack = $stackUtils.normalizedStack(err)
const newMessage = cb(err.message, newErrMsg)
const newStack = stackWithReplacedProps(err, { message: newMessage })
err.message = newMessage
err.stack = newStack
return err
}
const appendErrMsg = (err, errMsg) => {
return modifyErrMsg(err, errMsg, (msg1, msg2) => {
// we don't want to just throw in extra
// new lines if there isn't even a msg
if (!msg1) return msg2
if (!msg2) return msg1
return `${msg1}\n\n${msg2}`
})
}
const makeErrFromObj = (obj) => {
if (_.isString(obj)) {
return new Error(obj)
}
const err2 = new Error(obj.message)
err2.name = obj.name
err2.stack = obj.stack
_.each(obj, (val, prop) => {
if (!err2[prop]) {
err2[prop] = val
}
})
return err2
}
const makeErrFromErr = (err, options: any = {}) => {
if (_.isString(err)) {
err = cypressErr({ message: err })
}
let { onFail, errProps } = options
// assume onFail is a command if
// onFail is present and isn't a function
if (onFail && !_.isFunction(onFail)) {
const log = onFail
// redefine onFail and automatically
// hook this into our command
onFail = (err) => {
return log.error(err)
}
}
if (onFail) {
err.onFail = onFail
}
if (errProps) {
_.extend(err, errProps)
}
return err
}
const throwErr = (err, options: any = {}): never => {
throw makeErrFromErr(err, options)
}
const throwErrByPath = (errPath, options: any = {}): never => {
const err = errByPath(errPath, options.args)
if (options.stack) {
err.stack = $stackUtils.replacedStack(err, options.stack)
} else if (Error.captureStackTrace) {
// gets rid of internal stack lines that just build the error
Error.captureStackTrace(err, throwErrByPath)
}
throw makeErrFromErr(err, options)
}
const warnByPath = (errPath, options: any = {}) => {
const errObj = errByPath(errPath, options.args)
let err = errObj.message
const docsUrl = (errObj as CypressError).docsUrl
if (docsUrl) {
err += `\n\n${docsUrl}`
}
$utils.warning(err)
}
export class InternalCypressError extends Error {
onFail?: Function
isRecovered?: boolean
constructor (message) {
super(message)
this.name = 'InternalCypressError'
if (Error.captureStackTrace) {
Error.captureStackTrace(this, InternalCypressError)
}
}
}
export class CypressError extends Error {
docsUrl?: string
retry?: boolean
userInvocationStack?: any
onFail?: Function
isRecovered?: boolean
constructor (message) {
super(message)
this.name = 'CypressError'
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CypressError)
}
}
setUserInvocationStack (stack) {
this.userInvocationStack = stack
return this
}
}
const getUserInvocationStackFromError = (err) => {
return err.userInvocationStack
}
const internalErr = (err): InternalCypressError => {
const newErr = new InternalCypressError(err.message)
return mergeErrProps(newErr, err)
}
const cypressErr = (err): CypressError => {
const newErr = new CypressError(err.message)
return mergeErrProps(newErr, err) as CypressError
}
const cypressErrByPath = (errPath, options: any = {}) => {
const errObj = errByPath(errPath, options.args)
return cypressErr(errObj)
}
const replaceErrMsgTokens = (errMessage, args) => {
if (!errMessage) return errMessage
const replace = (str, argValue, argKey) => {
return str.replace(new RegExp(`\{\{${argKey}\}\}`, 'g'), argValue)
}
const getMsg = function (args = {}) {
return _.reduce(args, (message, argValue, argKey) => {
if (_.isArray(message)) {
return _.map(message, (str) => replace(str, argValue, argKey))
}
return replace(message, argValue, argKey)
}, errMessage)
}
// replace more than 2 newlines with exactly 2 newlines
return $utils.normalizeNewLines(getMsg(args), 2)
}
// recursively try for a default docsUrl
const docsUrlByParents = (msgPath) => {
msgPath = msgPath.split('.').slice(0, -1).join('.')
if (!msgPath) {
return // reached root
}
const obj = _.get($errorMessages, msgPath)
if (obj.hasOwnProperty('docsUrl')) {
return obj.docsUrl
}
return docsUrlByParents(msgPath)
}
const errByPath = (msgPath, args?) => {
let msgValue = _.get($errorMessages, msgPath)
if (!msgValue) {
return internalErr({ message: `Error message path '${msgPath}' does not exist` })
}
let msgObj = msgValue
if (_.isFunction(msgValue)) {
msgObj = msgValue(args)
}
if (_.isString(msgObj)) {
msgObj = {
message: msgObj,
}
}
const docsUrl = (msgObj.hasOwnProperty('docsUrl') && msgObj.docsUrl) || docsUrlByParents(msgPath)
return cypressErr({
message: replaceErrMsgTokens(msgObj.message, args),
docsUrl: docsUrl ? replaceErrMsgTokens(docsUrl, args) : undefined,
})
}
const createUncaughtException = ({ frameType, handlerType, state, err }) => {
const errPath = frameType === 'spec' ? 'uncaught.fromSpec' : 'uncaught.fromApp'
let uncaughtErr = errByPath(errPath, {
errMsg: stripAnsi(err.message),
promiseAddendum: handlerType === 'unhandledrejection' ? ' It was caused by an unhandled promise rejection.' : '',
}) as CypressError
err = modifyErrMsg(err, uncaughtErr.message, () => uncaughtErr.message)
err.docsUrl = _.compact([uncaughtErr.docsUrl, err.docsUrl])
const current = state('current')
err.onFail = () => {
current?.getLastLog()?.error(err)
}
return err
}
// stacks from command failures and assertion failures have the right message
// but the stack points to cypress internals. here we replace the internal
// cypress stack with the invocation stack, which points to the user's code
const stackAndCodeFrameIndex = (err, userInvocationStack): StackAndCodeFrameIndex => {
if (!userInvocationStack) return { stack: err.stack }
if (isCypressErr(err) || isChaiValidationErr(err)) {
return $stackUtils.stackWithUserInvocationStackSpliced(err, userInvocationStack)
}
return { stack: $stackUtils.replacedStack(err, userInvocationStack) || '' }
}
const preferredStackAndCodeFrameIndex = (err, userInvocationStack) => {
let { stack, index } = stackAndCodeFrameIndex(err, userInvocationStack)
stack = $stackUtils.stackWithContentAppended(err, stack)
stack = $stackUtils.stackWithReplacementMarkerLineRemoved(stack)
return { stack, index }
}
const enhanceStack = ({ err, userInvocationStack, projectRoot }: {
err: any
userInvocationStack?: any
projectRoot?: any
}) => {
const { stack, index } = preferredStackAndCodeFrameIndex(err, userInvocationStack)
const { sourceMapped, parsed } = $stackUtils.getSourceStack(stack, projectRoot)
err.stack = sourceMapped
err.parsedStack = parsed
err.codeFrame = $stackUtils.getCodeFrame(err, index)
return err
}
// all errors flow through this function before they're finally thrown
// or used to reject promises
const processErr = (errObj: CypressError, config) => {
let docsUrl = errObj.docsUrl
if (config('isInteractive') || !docsUrl) {
return errObj
}
// backup, and then delete the docsUrl property in runMode
// so that it does not add the 'Learn More' link to the UI
// for screenshots or videos
delete errObj.docsUrl
docsUrl = _(docsUrl).castArray().compact().join('\n\n')
// append the docs url when not interactive so it appears in the stdout
return appendErrMsg(errObj, docsUrl)
}
const getStackFromErrArgs = ({ filename, lineno, colno }) => {
if (!filename) return undefined
const line = lineno != null ? `:${lineno}` : ''
const column = lineno != null && colno != null ? `:${colno}` : ''
return ` at <unknown> (${filename}${line}${column})`
}
const convertErrorEventPropertiesToObject = (args) => {
let { message, filename, lineno, colno, err } = args
// if the error was thrown as a string (throw 'some error'), `err` is
// the message ('some error') and message is some browser-created
// variant (e.g. 'Uncaught some error')
message = _.isString(err) ? err : message
const stack = getStackFromErrArgs({ filename, lineno, colno })
return makeErrFromObj({
name: 'Error',
message,
stack,
})
}
export interface ErrorFromErrorEvent {
originalErr: Error
err: Error
}
const errorFromErrorEvent = (event): ErrorFromErrorEvent => {
let { message, filename, lineno, colno, error } = event
let docsUrl = error?.docsUrl
// reset the message on a cross origin script error
// since no details are accessible
if (crossOriginScriptRe.test(message)) {
const crossOriginErr = errByPath('uncaught.cross_origin_script') as CypressError
message = crossOriginErr.message
docsUrl = crossOriginErr.docsUrl
}
// it's possible the error was thrown as a string (throw 'some error')
// so create it in the case it's not already an object
const err = (_.isObject(error) ? error : convertErrorEventPropertiesToObject({
message, filename, lineno, colno,
})) as CypressError
err.docsUrl = docsUrl
// makeErrFromObj clones the error, so the original doesn't get mutated
return {
originalErr: err,
err: makeErrFromObj(err),
}
}
export interface ErrorFromProjectRejectionEvent extends ErrorFromErrorEvent {
promise: Promise<any>
}
const errorFromProjectRejectionEvent = (event): ErrorFromProjectRejectionEvent => {
// Bluebird triggers "unhandledrejection" with its own custom error event
// where the `promise` and `reason` are attached to event.detail
// http://bluebirdjs.com/docs/api/error-management-configuration.html
if (event.detail) {
event = event.detail
}
// makeErrFromObj clones the error, so the original doesn't get mutated
return {
originalErr: event.reason,
err: makeErrFromObj(event.reason),
promise: event.promise,
}
}
const errorFromUncaughtEvent = (handlerType: HandlerType, event) => {
return handlerType === 'error' ?
errorFromErrorEvent(event) :
errorFromProjectRejectionEvent(event)
}
const logError = (Cypress, handlerType: HandlerType, err: unknown, handled = false) => {
const error = toLoggableError(err)
Cypress.log({
message: `${error.name || 'Error'}: ${error.message}`,
name: 'uncaught exception',
type: 'parent',
// specifying the error causes the log to be red/failed
// otherwise, if it's been handled, we omit the error so it is grey/passed
error: handled ? undefined : err,
snapshot: true,
event: true,
timeout: 0,
end: true,
consoleProps: () => {
const consoleObj = {
'Caught By': `"${handlerType}" handler`,
'Error': err,
}
return consoleObj
},
})
}
interface LoggableError { name?: string, message: string }
const isLoggableError = (error: unknown): error is LoggableError => {
return (
typeof error === 'object' &&
error !== null &&
'message' in error)
}
const toLoggableError = (maybeError: unknown): LoggableError => {
if (isLoggableError(maybeError)) return maybeError
try {
return { message: JSON.stringify(maybeError) }
} catch {
return { message: String(maybeError) }
}
}
const getUnsupportedPlugin = (runnable) => {
if (!(runnable.invocationDetails && runnable.invocationDetails.originalFile && runnable.err && runnable.err.message)) {
return null
}
const pluginsErrors = {
'@cypress/code-coverage': 'glob pattern string required',
}
const unsupportedPluginFound = Object.keys(pluginsErrors).find((plugin) => runnable.invocationDetails.originalFile.includes(plugin))
if (unsupportedPluginFound && pluginsErrors[unsupportedPluginFound] && runnable.err.message.includes(pluginsErrors[unsupportedPluginFound])) {
return unsupportedPluginFound
}
return null
}
export default {
stackWithReplacedProps,
appendErrMsg,
createUncaughtException,
cypressErr,
cypressErrByPath,
enhanceStack,
errByPath,
errorFromUncaughtEvent,
getUnsupportedPlugin,
getUserInvocationStack,
getUserInvocationStackFromError,
isAssertionErr,
isChaiValidationErr,
isCypressErr,
isSpecError,
logError,
makeErrFromObj,
mergeErrProps,
modifyErrMsg,
processErr,
throwErr,
throwErrByPath,
warnByPath,
wrapErr,
}