Unverified Commit 5f258858 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[devtools] Show `AggregateError.errors` in the error overlay (#91835)

parent 3cbf85d1
import { useMemo } from 'react'
import React from 'react'
import { CodeFrame } from '../../components/code-frame/code-frame'
import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack'
import { ErrorCause } from './error-cause'
import type { ReadyErrorCause } from '../../utils/get-error-by-type'
interface ErrorAggregateErrorsProps {
errors: ReadyErrorCause[]
dialogResizerRef: React.RefObject<HTMLDivElement | null>
}
export function ErrorAggregateErrors({
errors,
dialogResizerRef,
}: ErrorAggregateErrorsProps) {
return (
// TODO: Wrap in SuspenseList
<>
{errors.map((entry, index) => (
<ErrorAggregateEntry
key={index}
entry={entry}
index={index}
total={errors.length}
dialogResizerRef={dialogResizerRef}
/>
))}
</>
)
}
interface ErrorAggregateEntryProps {
entry: ReadyErrorCause
index: number
total: number
dialogResizerRef: React.RefObject<HTMLDivElement | null>
}
function ErrorAggregateEntry({
entry,
index,
total,
dialogResizerRef,
}: ErrorAggregateEntryProps) {
const frames = React.use(entry.frames())
const trimmedMessage = entry.error.message.trim()
const firstFrame = useMemo(() => {
const idx = frames.findIndex(
(f) =>
!f.ignored &&
Boolean(f.originalCodeFrame) &&
Boolean(f.originalStackFrame)
)
return frames[idx] ?? null
}, [frames])
return (
<div data-nextjs-error-aggregate-error>
<div className="error-aggregate-error-header">
<span className="error-aggregate-error-label">
{index + 1} of {total}: {entry.error.name || 'Error'}
</span>
</div>
{trimmedMessage ? (
<p className="error-aggregate-error-message">{trimmedMessage}</p>
) : null}
{firstFrame && (
<CodeFrame
stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame!}
/>
)}
{frames.length > 0 && (
<ErrorOverlayCallStack
dialogResizerRef={dialogResizerRef}
frames={frames}
/>
)}
{entry.cause && (
<ErrorCause cause={entry.cause} dialogResizerRef={dialogResizerRef} />
)}
{'aggregateErrors' in entry && entry.aggregateErrors !== null && (
<ErrorAggregateErrors
errors={entry.aggregateErrors}
dialogResizerRef={dialogResizerRef}
/>
)}
</div>
)
}
export const styles = `
[data-nextjs-error-aggregate-error] {
border-top: 1px solid var(--color-gray-400);
margin-top: 16px;
padding-top: 16px;
}
.error-aggregate-error-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.error-aggregate-error-label {
padding: 2px 6px;
margin: 0;
border-radius: var(--rounded-md-2);
background: var(--color-red-100);
font-weight: 600;
font-size: var(--size-12);
color: var(--color-red-900);
font-family: var(--font-stack-monospace);
line-height: var(--size-20);
}
.error-aggregate-error-message {
margin: 0;
margin-left: 4px;
color: var(--color-red-900);
font-weight: 500;
font-size: var(--size-16);
letter-spacing: -0.32px;
line-height: var(--size-24);
overflow-wrap: break-word;
white-space: pre-wrap;
}
`
...@@ -2,6 +2,7 @@ import { useMemo } from 'react' ...@@ -2,6 +2,7 @@ import { useMemo } from 'react'
import React from 'react' import React from 'react'
import { CodeFrame } from '../../components/code-frame/code-frame' import { CodeFrame } from '../../components/code-frame/code-frame'
import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack' import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack'
import { ErrorAggregateErrors } from './error-aggregate-errors'
import type { ReadyErrorCause } from '../../utils/get-error-by-type' import type { ReadyErrorCause } from '../../utils/get-error-by-type'
type ErrorCauseProps = { type ErrorCauseProps = {
...@@ -51,6 +52,13 @@ export function ErrorCause({ cause, dialogResizerRef }: ErrorCauseProps) { ...@@ -51,6 +52,13 @@ export function ErrorCause({ cause, dialogResizerRef }: ErrorCauseProps) {
{cause.cause && ( {cause.cause && (
<ErrorCause cause={cause.cause} dialogResizerRef={dialogResizerRef} /> <ErrorCause cause={cause.cause} dialogResizerRef={dialogResizerRef} />
)} )}
{'aggregateErrors' in cause && cause.aggregateErrors !== null && (
<ErrorAggregateErrors
errors={cause.aggregateErrors}
dialogResizerRef={dialogResizerRef}
/>
)}
</div> </div>
) )
} }
......
...@@ -3,6 +3,10 @@ import { CodeFrame } from '../../components/code-frame/code-frame' ...@@ -3,6 +3,10 @@ import { CodeFrame } from '../../components/code-frame/code-frame'
import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack' import { ErrorOverlayCallStack } from '../../components/errors/error-overlay-call-stack/error-overlay-call-stack'
import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html' import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html'
import { ErrorCause, styles as errorCauseStyles } from './error-cause' import { ErrorCause, styles as errorCauseStyles } from './error-cause'
import {
ErrorAggregateErrors,
styles as errorAggregateErrorsStyles,
} from './error-aggregate-errors'
import { import {
useFrames, useFrames,
type ReadyRuntimeError, type ReadyRuntimeError,
...@@ -46,6 +50,13 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { ...@@ -46,6 +50,13 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
{error.cause && ( {error.cause && (
<ErrorCause cause={error.cause} dialogResizerRef={dialogResizerRef} /> <ErrorCause cause={error.cause} dialogResizerRef={dialogResizerRef} />
)} )}
{'aggregateErrors' in error && error.aggregateErrors !== null && (
<ErrorAggregateErrors
errors={error.aggregateErrors}
dialogResizerRef={dialogResizerRef}
/>
)}
</> </>
) )
} }
...@@ -53,4 +64,5 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { ...@@ -53,4 +64,5 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
export const styles = ` export const styles = `
${PSEUDO_HTML_DIFF_STYLES} ${PSEUDO_HTML_DIFF_STYLES}
${errorCauseStyles} ${errorCauseStyles}
${errorAggregateErrorsStyles}
` `
...@@ -5,20 +5,37 @@ import { getErrorSource } from '../../../shared/lib/error-source' ...@@ -5,20 +5,37 @@ import { getErrorSource } from '../../../shared/lib/error-source'
import { parseStack } from '../../../server/lib/parse-stack' import { parseStack } from '../../../server/lib/parse-stack'
import React from 'react' import React from 'react'
export type ReadyErrorCause = { export type ReadyErrorCause =
error: Error | {
frames: () => Promise<readonly OriginalStackFrame[]> error: Error
cause?: ReadyErrorCause frames: () => Promise<readonly OriginalStackFrame[]>
} cause?: ReadyErrorCause
}
| {
error: AggregateError
frames: () => Promise<readonly OriginalStackFrame[]>
cause?: ReadyErrorCause
aggregateErrors: ReadyErrorCause[] | null
}
export type ReadyRuntimeError = { export type ReadyRuntimeError =
id: number | {
runtime: true id: number
error: Error & { environmentName?: string } runtime: true
frames: () => Promise<readonly OriginalStackFrame[]> error: Error & { environmentName?: string }
type: 'runtime' | 'console' | 'recoverable' frames: () => Promise<readonly OriginalStackFrame[]>
cause?: ReadyErrorCause type: 'runtime' | 'console' | 'recoverable'
} cause?: ReadyErrorCause
}
| {
id: number
runtime: true
error: AggregateError & { environmentName?: string }
frames: () => Promise<readonly OriginalStackFrame[]>
type: 'runtime' | 'console' | 'recoverable'
cause?: ReadyErrorCause
aggregateErrors: ReadyErrorCause[] | null
}
export const useFrames = ( export const useFrames = (
error: ReadyRuntimeError | null error: ReadyRuntimeError | null
...@@ -33,22 +50,42 @@ export function getErrorByType( ...@@ -33,22 +50,42 @@ export function getErrorByType(
event: SupportedErrorEvent, event: SupportedErrorEvent,
isAppDir: boolean isAppDir: boolean
): ReadyRuntimeError { ): ReadyRuntimeError {
const readyRuntimeError: ReadyRuntimeError = { if (event.error instanceof AggregateError) {
id: event.id, const readyRuntimeError: ReadyRuntimeError = {
runtime: true, id: event.id,
error: event.error, runtime: true,
type: event.type, error: event.error,
// createMemoizedPromise dedups calls to getOriginalStackFrames type: event.type,
frames: createMemoizedPromise(async () => { // createMemoizedPromise dedups calls to getOriginalStackFrames
return await getOriginalStackFrames( frames: createMemoizedPromise(async () => {
event.frames, return await getOriginalStackFrames(
getErrorSource(event.error), event.frames,
isAppDir getErrorSource(event.error),
) isAppDir
}), )
cause: getCauseChain(event.error, isAppDir), }),
cause: getCauseChain(event.error, isAppDir),
aggregateErrors: getAggregateErrors(event.error, isAppDir),
}
return readyRuntimeError
} else {
const readyRuntimeError: ReadyRuntimeError = {
id: event.id,
runtime: true,
error: event.error,
type: event.type,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
event.frames,
getErrorSource(event.error),
isAppDir
)
}),
cause: getCauseChain(event.error, isAppDir),
}
return readyRuntimeError
} }
return readyRuntimeError
} }
function getCauseChain( function getCauseChain(
...@@ -61,17 +98,85 @@ function getCauseChain( ...@@ -61,17 +98,85 @@ function getCauseChain(
if (!(cause instanceof Error)) return undefined if (!(cause instanceof Error)) return undefined
const frames = parseStack(cause.stack || '') const frames = parseStack(cause.stack || '')
return { if (cause instanceof AggregateError) {
error: cause, return {
frames: createMemoizedPromise(async () => { error: cause,
return await getOriginalStackFrames( frames: createMemoizedPromise(async () => {
frames, return await getOriginalStackFrames(
getErrorSource(cause), frames,
isAppDir getErrorSource(cause),
) isAppDir
}), )
cause: getCauseChain(cause, isAppDir, depth + 1), }),
cause: getCauseChain(cause, isAppDir, depth + 1),
aggregateErrors: getAggregateErrors(cause, isAppDir, depth + 1),
}
} else {
return {
error: cause,
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
frames,
getErrorSource(cause),
isAppDir
)
}),
cause: getCauseChain(cause, isAppDir, depth + 1),
}
}
}
function getAggregateErrors(
error: AggregateError,
isAppDir: boolean,
depth: number = 0
): ReadyErrorCause[] | null {
if (depth >= 5) {
return null
}
if (error.errors.length === 0) {
return null
}
const maxErrors = 5
const readyErrors: ReadyErrorCause[] = []
for (let i = 0; i < error.errors.length; i++) {
const childError = error.errors[i]
if (childError instanceof AggregateError) {
const frames = parseStack(childError.stack || '')
readyErrors.push({
error: childError,
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
frames,
getErrorSource(childError),
isAppDir
)
}),
cause: getCauseChain(childError, isAppDir, depth + 1),
aggregateErrors: getAggregateErrors(childError, isAppDir, depth + 1),
})
} else if (childError instanceof Error) {
const frames = parseStack(childError.stack || '')
readyErrors.push({
error: childError,
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
frames,
getErrorSource(childError),
isAppDir
)
}),
cause: getCauseChain(childError, isAppDir, depth + 1),
})
}
if (readyErrors.length >= maxErrors) {
break
}
} }
return readyErrors
} }
function createMemoizedPromise<T>( function createMemoizedPromise<T>(
......
'use client'
import React from 'react'
export default function Page() {
const agg = new AggregateError(
['string error', 42, new Error('Real error')],
'Mixed errors'
)
console.error(agg)
return <p>Check Redbox</p>
}
'use client'
import React from 'react'
export default function Page() {
const root = new TypeError('Connection refused')
const error1 = new Error('Database query failed', { cause: root })
const error2 = new Error('Cache miss')
const agg = new AggregateError([error1, error2], 'Multiple failures occurred')
console.error(agg)
return <p>Check Redbox</p>
}
'use client'
import React from 'react'
export default function Page() {
const error1 = new Error('Error one')
const error2 = new TypeError('Error two')
const agg = new AggregateError([error1, error2], 'Multiple errors occurred')
console.error(agg)
return <p>Check Redbox</p>
}
...@@ -184,6 +184,128 @@ describe('DevErrorOverlay', () => { ...@@ -184,6 +184,128 @@ describe('DevErrorOverlay', () => {
`) `)
}) })
it('shows AggregateError.errors in the error overlay', async () => {
const browser = await next.browser('/error-aggregate')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"aggregateErrors": [
{
"label": "1 of 2: Error",
"message": "Error one",
"source": "app/error-aggregate/page.tsx (6:18) @ Page
> 6 | const error1 = new Error('Error one')
| ^",
"stack": [
"Page app/error-aggregate/page.tsx (6:18)",
],
},
{
"label": "2 of 2: TypeError",
"message": "Error two",
"source": "app/error-aggregate/page.tsx (7:18) @ Page
> 7 | const error2 = new TypeError('Error two')
| ^",
"stack": [
"Page app/error-aggregate/page.tsx (7:18)",
],
},
],
"description": "Multiple errors occurred",
"environmentLabel": null,
"label": "Console AggregateError",
"source": "app/error-aggregate/page.tsx (8:15) @ Page
> 8 | const agg = new AggregateError([error1, error2], 'Multiple errors occurred')
| ^",
"stack": [
"Page app/error-aggregate/page.tsx (8:15)",
],
}
`)
})
it('shows AggregateError.errors with cause chains in the error overlay', async () => {
const browser = await next.browser('/error-aggregate-with-cause')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"aggregateErrors": [
{
"label": "1 of 2: Error",
"message": "Database query failed",
"source": "app/error-aggregate-with-cause/page.tsx (7:18) @ Page
> 7 | const error1 = new Error('Database query failed', { cause: root })
| ^",
"stack": [
"Page app/error-aggregate-with-cause/page.tsx (7:18)",
],
},
{
"label": "2 of 2: Error",
"message": "Cache miss",
"source": "app/error-aggregate-with-cause/page.tsx (8:18) @ Page
> 8 | const error2 = new Error('Cache miss')
| ^",
"stack": [
"Page app/error-aggregate-with-cause/page.tsx (8:18)",
],
},
],
"cause": [
{
"label": "Caused by: TypeError",
"message": "Connection refused",
"source": "app/error-aggregate-with-cause/page.tsx (6:16) @ Page
> 6 | const root = new TypeError('Connection refused')
| ^",
"stack": [
"Page app/error-aggregate-with-cause/page.tsx (6:16)",
],
},
],
"description": "Multiple failures occurred",
"environmentLabel": null,
"label": "Console AggregateError",
"source": "app/error-aggregate-with-cause/page.tsx (9:15) @ Page
> 9 | const agg = new AggregateError([error1, error2], 'Multiple failures occurred')
| ^",
"stack": [
"Page app/error-aggregate-with-cause/page.tsx (9:15)",
],
}
`)
})
it('filters non-Error items from AggregateError.errors', async () => {
const browser = await next.browser('/error-aggregate-non-errors')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"aggregateErrors": [
{
"label": "1 of 1: Error",
"message": "Real error",
"source": "app/error-aggregate-non-errors/page.tsx (7:26) @ Page
> 7 | ['string error', 42, new Error('Real error')],
| ^",
"stack": [
"Page app/error-aggregate-non-errors/page.tsx (7:26)",
],
},
],
"description": "Mixed errors",
"environmentLabel": null,
"label": "Console AggregateError",
"source": "app/error-aggregate-non-errors/page.tsx (6:15) @ Page
> 6 | const agg = new AggregateError(
| ^",
"stack": [
"Page app/error-aggregate-non-errors/page.tsx (6:15)",
],
}
`)
})
it('should load dev overlay styles successfully', async () => { it('should load dev overlay styles successfully', async () => {
const browser = await next.browser('/hydration-error') const browser = await next.browser('/hydration-error')
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
waitForRedbox, waitForRedbox,
getRedboxCallStack, getRedboxCallStack,
getRedboxCause, getRedboxCause,
getRedboxAggregateErrors,
getRedboxComponentStack, getRedboxComponentStack,
getRedboxDescription, getRedboxDescription,
getRedboxEnvironmentLabel, getRedboxEnvironmentLabel,
...@@ -87,6 +88,7 @@ export interface ErrorSnapshot { ...@@ -87,6 +88,7 @@ export interface ErrorSnapshot {
description?: string description?: string
componentStack?: string componentStack?: string
cause?: SanitizedCauseEntry[] cause?: SanitizedCauseEntry[]
aggregateErrors?: SanitizedCauseEntry[]
code?: string code?: string
source: string | null source: string | null
stack: string[] | null stack: string[] | null
...@@ -193,6 +195,7 @@ async function createErrorSnapshot( ...@@ -193,6 +195,7 @@ async function createErrorSnapshot(
stack, stack,
componentStack, componentStack,
cause, cause,
aggregateErrors,
code, code,
] = await Promise.all([ ] = await Promise.all([
includeLabel ? getRedboxLabel(browser) : null, includeLabel ? getRedboxLabel(browser) : null,
...@@ -202,6 +205,7 @@ async function createErrorSnapshot( ...@@ -202,6 +205,7 @@ async function createErrorSnapshot(
getRedboxCallStack(browser), getRedboxCallStack(browser),
getRedboxComponentStack(browser), getRedboxComponentStack(browser),
getRedboxCause(browser), getRedboxCause(browser),
getRedboxAggregateErrors(browser),
getRedboxErrorCode(browser), getRedboxErrorCode(browser),
]) ])
...@@ -276,6 +280,21 @@ async function createErrorSnapshot( ...@@ -276,6 +280,21 @@ async function createErrorSnapshot(
}) })
} }
// AggregateError.errors are only relevant when present.
if (aggregateErrors !== null) {
snapshot.aggregateErrors = aggregateErrors.map((entry) => {
const aggEntry: SanitizedCauseEntry = {
label: entry.label,
source: focusSource(entry.source, next),
stack: sanitizeStack(entry.stack, next) ?? [],
}
if (entry.message !== null) {
aggEntry.message = entry.message
}
return aggEntry
})
}
return snapshot return snapshot
} }
......
...@@ -1649,6 +1649,49 @@ export async function getRedboxCause( ...@@ -1649,6 +1649,49 @@ export async function getRedboxCause(
}) })
} }
export async function getRedboxAggregateErrors(
browser: Playwright
): Promise<RedboxCauseEntry[] | null> {
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
const root = portal?.shadowRoot
const aggregateElements = root?.querySelectorAll(
'[data-nextjs-error-aggregate-error]'
)
if (!aggregateElements || aggregateElements.length === 0) return null
const entries: {
label: string | null
message: string | null
source: string | null
stack: string[]
}[] = []
for (const el of aggregateElements) {
const stackFrameElements = el.querySelectorAll(
':scope > [data-nextjs-call-stack-container] > [data-nextjs-call-stack-frame]'
)
const stack: string[] = []
for (const frameEl of stackFrameElements) {
stack.push(frameEl.innerText.replace(/\n+/g, ' '))
}
entries.push({
label:
el.querySelector('.error-aggregate-error-label')?.innerText ?? null,
message:
el.querySelector('.error-aggregate-error-message')?.innerText ?? null,
source:
el.querySelector(':scope > [data-nextjs-codeframe]')?.innerText ??
null,
stack,
})
}
return entries
})
}
export async function getRedboxCallStack( export async function getRedboxCallStack(
browser: Playwright browser: Playwright
): Promise<string[] | null> { ): Promise<string[] | null> {
...@@ -1665,8 +1708,11 @@ export async function getRedboxCallStack( ...@@ -1665,8 +1708,11 @@ export async function getRedboxCallStack(
if (frameElements !== undefined) { if (frameElements !== undefined) {
let foundInternalFrame = false let foundInternalFrame = false
for (const frameElement of frameElements) { for (const frameElement of frameElements) {
// Skip frames that belong to an Error.cause section // Skip frames that belong to an Error.cause or AggregateError section
if (frameElement.closest('[data-nextjs-error-cause]')) { if (
frameElement.closest('[data-nextjs-error-cause]') ||
frameElement.closest('[data-nextjs-error-aggregate-error]')
) {
continue continue
} }
// `innerText` will be "${methodName}\n${location}". // `innerText` will be "${methodName}\n${location}".
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment