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

[devtools] Add support for error causes in the dev overlay (#90108)

parent 4d3b2507
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 type { ReadyErrorCause } from '../../utils/get-error-by-type'
type ErrorCauseProps = {
cause: ReadyErrorCause
dialogResizerRef: React.RefObject<HTMLDivElement | null>
}
export function ErrorCause({ cause, dialogResizerRef }: ErrorCauseProps) {
const frames = React.use(cause.frames())
const firstFrame = useMemo(() => {
const index = frames.findIndex(
(entry) =>
!entry.ignored &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
return frames[index] ?? null
}, [frames])
return (
<div data-nextjs-error-cause>
<div className="error-cause-header">
<span className="error-cause-label">
Caused by: {cause.error.name || 'Error'}
</span>
</div>
<p className="error-cause-message">{cause.error.message}</p>
{firstFrame && (
<CodeFrame
stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame!}
/>
)}
{frames.length > 0 && (
<ErrorOverlayCallStack
dialogResizerRef={dialogResizerRef}
frames={frames}
/>
)}
{cause.cause && (
<ErrorCause cause={cause.cause} dialogResizerRef={dialogResizerRef} />
)}
</div>
)
}
export const styles = `
[data-nextjs-error-cause] {
border-top: 1px solid var(--color-gray-400);
margin-top: 16px;
padding-top: 16px;
}
.error-cause-header {
display: flex;
align-items: center;
margin-bottom: 8px;
}
.error-cause-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-cause-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 { 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 { 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 { import {
useFrames, useFrames,
type ReadyRuntimeError, type ReadyRuntimeError,
...@@ -41,10 +42,15 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { ...@@ -41,10 +42,15 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
frames={frames} frames={frames}
/> />
)} )}
{error.cause && (
<ErrorCause cause={error.cause} dialogResizerRef={dialogResizerRef} />
)}
</> </>
) )
} }
export const styles = ` export const styles = `
${PSEUDO_HTML_DIFF_STYLES} ${PSEUDO_HTML_DIFF_STYLES}
${errorCauseStyles}
` `
...@@ -2,14 +2,22 @@ import type { SupportedErrorEvent } from '../container/runtime-error/render-erro ...@@ -2,14 +2,22 @@ import type { SupportedErrorEvent } from '../container/runtime-error/render-erro
import { getOriginalStackFrames } from '../../shared/stack-frame' import { getOriginalStackFrames } from '../../shared/stack-frame'
import type { OriginalStackFrame } from '../../shared/stack-frame' import type { OriginalStackFrame } from '../../shared/stack-frame'
import { getErrorSource } from '../../../shared/lib/error-source' import { getErrorSource } from '../../../shared/lib/error-source'
import { parseStack } from '../../../server/lib/parse-stack'
import React from 'react' import React from 'react'
export type ReadyErrorCause = {
error: Error
frames: () => Promise<readonly OriginalStackFrame[]>
cause?: ReadyErrorCause
}
export type ReadyRuntimeError = { export type ReadyRuntimeError = {
id: number id: number
runtime: true runtime: true
error: Error & { environmentName?: string } error: Error & { environmentName?: string }
frames: () => Promise<readonly OriginalStackFrame[]> frames: () => Promise<readonly OriginalStackFrame[]>
type: 'runtime' | 'console' | 'recoverable' type: 'runtime' | 'console' | 'recoverable'
cause?: ReadyErrorCause
} }
export const useFrames = ( export const useFrames = (
...@@ -38,10 +46,34 @@ export function getErrorByType( ...@@ -38,10 +46,34 @@ export function getErrorByType(
isAppDir isAppDir
) )
}), }),
cause: getCauseChain(event.error, isAppDir),
} }
return readyRuntimeError return readyRuntimeError
} }
function getCauseChain(
error: Error,
isAppDir: boolean,
depth: number = 0
): ReadyErrorCause | undefined {
if (depth >= 5) return undefined
const cause = error.cause
if (!(cause instanceof Error)) return undefined
const frames = parseStack(cause.stack || '')
return {
error: cause,
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
frames,
getErrorSource(cause),
isAppDir
)
}),
cause: getCauseChain(cause, isAppDir, depth + 1),
}
}
function createMemoizedPromise<T>( function createMemoizedPromise<T>(
promiseFactory: () => Promise<T> promiseFactory: () => Promise<T>
): () => Promise<T> { ): () => Promise<T> {
......
'use client'
import React from 'react'
export default function Page() {
const root = new TypeError('Connection refused')
const mid = new Error('Database query failed', { cause: root })
const top = new Error('Failed to load user', { cause: mid })
console.error(top)
return <p>Check Redbox</p>
}
'use client'
import React from 'react'
export default function Page() {
const err = new Error('Something went wrong', {
cause: 'a plain string cause',
})
console.error(err)
return <p>Check Redbox</p>
}
'use client'
import React from 'react'
export default function Page() {
const root = new TypeError('Connection refused')
const mid = new Error('Database query failed', { cause: root })
console.error(mid)
return <p>Check Redbox</p>
}
...@@ -96,6 +96,94 @@ describe('DevErrorOverlay', () => { ...@@ -96,6 +96,94 @@ describe('DevErrorOverlay', () => {
} }
}) })
it('shows Error.cause in the error overlay', async () => {
const browser = await next.browser('/error-cause')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: TypeError",
"message": "Connection refused",
"source": "app/error-cause/page.tsx (6:16) @ Page
> 6 | const root = new TypeError('Connection refused')
| ^",
"stack": [
"Page app/error-cause/page.tsx (6:16)",
],
},
],
"description": "Database query failed",
"environmentLabel": null,
"label": "Console Error",
"source": "app/error-cause/page.tsx (7:15) @ Page
> 7 | const mid = new Error('Database query failed', { cause: root })
| ^",
"stack": [
"Page app/error-cause/page.tsx (7:15)",
],
}
`)
})
it('shows nested Error.cause chain in the error overlay', async () => {
const browser = await next.browser('/error-cause-nested')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Error",
"message": "Database query failed",
"source": "app/error-cause-nested/page.tsx (7:15) @ Page
> 7 | const mid = new Error('Database query failed', { cause: root })
| ^",
"stack": [
"Page app/error-cause-nested/page.tsx (7:15)",
],
},
{
"label": "Caused by: TypeError",
"message": "Connection refused",
"source": "app/error-cause-nested/page.tsx (6:16) @ Page
> 6 | const root = new TypeError('Connection refused')
| ^",
"stack": [
"Page app/error-cause-nested/page.tsx (6:16)",
],
},
],
"description": "Failed to load user",
"environmentLabel": null,
"label": "Console Error",
"source": "app/error-cause-nested/page.tsx (8:15) @ Page
> 8 | const top = new Error('Failed to load user', { cause: mid })
| ^",
"stack": [
"Page app/error-cause-nested/page.tsx (8:15)",
],
}
`)
})
it('ignores non-Error cause in the error overlay', async () => {
const browser = await next.browser('/error-cause-non-error')
await expect({ browser, next }).toDisplayCollapsedRedbox(`
{
"description": "Something went wrong",
"environmentLabel": null,
"label": "Console Error",
"source": "app/error-cause-non-error/page.tsx (6:15) @ Page
> 6 | const err = new Error('Something went wrong', {
| ^",
"stack": [
"Page app/error-cause-non-error/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')
......
...@@ -3,6 +3,7 @@ import { toMatchInlineSnapshot } from 'jest-snapshot' ...@@ -3,6 +3,7 @@ import { toMatchInlineSnapshot } from 'jest-snapshot'
import { import {
waitForRedbox, waitForRedbox,
getRedboxCallStack, getRedboxCallStack,
getRedboxCause,
getRedboxComponentStack, getRedboxComponentStack,
getRedboxDescription, getRedboxDescription,
getRedboxEnvironmentLabel, getRedboxEnvironmentLabel,
...@@ -72,29 +73,133 @@ interface ErrorSnapshotOptions { ...@@ -72,29 +73,133 @@ interface ErrorSnapshotOptions {
label?: boolean label?: boolean
} }
interface SanitizedCauseEntry {
label: string | null
message: string | null
source: string | null
stack: string[]
}
export interface ErrorSnapshot { export interface ErrorSnapshot {
environmentLabel: string | null environmentLabel: string | null
label: string | null label: string | null
description: string | null description: string | null
componentStack?: string componentStack?: string
cause?: SanitizedCauseEntry[]
source: string | null source: string | null
stack: string[] | null stack: string[] | null
} }
/**
* Focus source to just the header, errored line, and cursor.
* Strips surrounding context lines.
*/
function focusSource(
source: string | null,
next: NextInstance | null
): string | null {
if (source === null) return null
let focusedSource = ''
const sourceFrameLines = source.split('\n')
for (let i = 0; i < sourceFrameLines.length; i++) {
const sourceFrameLine = sourceFrameLines[i].trimEnd()
if (sourceFrameLine === '') {
continue
}
if (sourceFrameLine.startsWith('>')) {
// This is where the cursor will point
// Include the cursor and nothing below since it's just surrounding code.
focusedSource += '\n' + sourceFrameLine
focusedSource += '\n' + sourceFrameLines[i + 1]
break
}
const isCodeFrameLine = /^ {2}\s*\d+ \|/.test(sourceFrameLine)
if (!isCodeFrameLine) {
focusedSource += '\n' + sourceFrameLine
}
}
focusedSource = focusedSource.trim()
if (next !== null) {
focusedSource = focusedSource.replaceAll(
next.testDir,
'<FIXME-project-root>'
)
}
// This is the processed path the nextjs file from node_modules,
// likely not being processed properly and it's not deterministic among tests.
// e.g. it could be a encoded url of loader path:
// ../packages/next/dist/build/webpack/loaders/next-app-loader/index.js...
const sourceLines = focusedSource.split('\n')
if (
sourceLines[0].startsWith('./node_modules/.pnpm/next@file+') ||
sourceLines[0].startsWith('./node_modules/.pnpm/file+') ||
// e.g. "next-app-loader?<SEARCH PARAMS>" (in rspack, the loader doesn't seem to be prefixed with node_modules)
/^next-[a-zA-Z0-9\-_]+?-loader\?/.test(sourceLines[0])
) {
focusedSource = `<FIXME-nextjs-internal-source>\n${sourceLines.slice(1).join('\n')}`
}
return focusedSource
}
/**
* Sanitize stack frames: collapse internal frames, replace project root.
*/
function sanitizeStack(
stack: string[] | null,
next: NextInstance | null
): string[] | null {
if (stack === null) return null
const sanitized: string[] = []
let foundInternalFrame = false
for (const frame of stack) {
const isInternalFrame = / .\/dist\//.test(frame)
if (isInternalFrame) {
if (!foundInternalFrame) {
sanitized.push('<FIXME-internal-frame>')
}
foundInternalFrame = true
} else if (frame.includes('file://')) {
sanitized.push('<FIXME-file-protocol>')
} else if (frame.includes('.next/')) {
sanitized.push('<FIXME-next-dist-dir>')
} else if (next !== null) {
sanitized.push(frame.replace(next.testDir, '<FIXME-project-root>'))
} else {
sanitized.push(frame)
}
}
return sanitized
}
async function createErrorSnapshot( async function createErrorSnapshot(
browser: Playwright, browser: Playwright,
next: NextInstance | null, next: NextInstance | null,
{ label: includeLabel = true }: ErrorSnapshotOptions = {} { label: includeLabel = true }: ErrorSnapshotOptions = {}
): Promise<ErrorSnapshot> { ): Promise<ErrorSnapshot> {
const [label, environmentLabel, description, source, stack, componentStack] = const [
await Promise.all([ label,
includeLabel ? getRedboxLabel(browser) : null, environmentLabel,
getRedboxEnvironmentLabel(browser), description,
getRedboxDescription(browser), source,
getRedboxSource(browser), stack,
getRedboxCallStack(browser), componentStack,
getRedboxComponentStack(browser), cause,
]) ] = await Promise.all([
includeLabel ? getRedboxLabel(browser) : null,
getRedboxEnvironmentLabel(browser),
getRedboxDescription(browser),
getRedboxSource(browser),
getRedboxCallStack(browser),
getRedboxComponentStack(browser),
getRedboxCause(browser),
])
// We don't need to test the codeframe logic everywhere. // We don't need to test the codeframe logic everywhere.
// Here we focus on the cursor position of the top most frame // Here we focus on the cursor position of the top most frame
...@@ -114,55 +219,7 @@ async function createErrorSnapshot( ...@@ -114,55 +219,7 @@ async function createErrorSnapshot(
// pages/index.js (3:11) @ Page // pages/index.js (3:11) @ Page
// > 3 | throw new Error("anonymous error!"); // > 3 | throw new Error("anonymous error!");
// | ^ // | ^
let focusedSource = source const focusedSource = focusSource(source, next)
if (source !== null) {
focusedSource = ''
const sourceFrameLines = source.split('\n')
for (let i = 0; i < sourceFrameLines.length; i++) {
const sourceFrameLine = sourceFrameLines[i].trimEnd()
if (sourceFrameLine === '') {
continue
}
if (sourceFrameLine.startsWith('>')) {
// This is where the cursor will point
// Include the cursor and nothing below since it's just surrounding code.
focusedSource += '\n' + sourceFrameLine
focusedSource += '\n' + sourceFrameLines[i + 1]
break
}
const isCodeFrameLine = /^ {2}\s*\d+ \|/.test(sourceFrameLine)
if (!isCodeFrameLine) {
focusedSource += '\n' + sourceFrameLine
}
}
focusedSource = focusedSource.trim()
if (next !== null) {
focusedSource = focusedSource.replaceAll(
next.testDir,
'<FIXME-project-root>'
)
}
// This is the processed path the nextjs file from node_modules,
// likely not being processed properly and it's not deterministic among tests.
// e.g. it could be a encoded url of loader path:
// ../packages/next/dist/build/webpack/loaders/next-app-loader/index.js...
const sourceLines = focusedSource.split('\n')
if (
sourceLines[0].startsWith('./node_modules/.pnpm/next@file+') ||
sourceLines[0].startsWith('./node_modules/.pnpm/file+') ||
// e.g. "next-app-loader?<SEARCH PARAMS>" (in rspack, the loader doesn't seem to be prefixed with node_modules)
/^next-[a-zA-Z0-9\-_]+?-loader\?/.test(sourceLines[0])
) {
focusedSource =
`<FIXME-nextjs-internal-source>` +
'\n' +
sourceLines.slice(1).join('\n')
}
}
let sanitizedDescription = description let sanitizedDescription = description
...@@ -184,12 +241,7 @@ async function createErrorSnapshot( ...@@ -184,12 +241,7 @@ async function createErrorSnapshot(
label: label ?? '<FIXME-excluded-label>', label: label ?? '<FIXME-excluded-label>',
description: sanitizedDescription, description: sanitizedDescription,
source: focusedSource, source: focusedSource,
stack: stack: sanitizeStack(stack, next),
next !== null && stack !== null
? stack.map((stackframe) => {
return stackframe.replace(next.testDir, '<FIXME-project-root>')
})
: stack,
} }
// Hydration diffs are only relevant to some specific errors // Hydration diffs are only relevant to some specific errors
...@@ -198,6 +250,16 @@ async function createErrorSnapshot( ...@@ -198,6 +250,16 @@ async function createErrorSnapshot(
snapshot.componentStack = componentStack snapshot.componentStack = componentStack
} }
// Error.cause chain is only relevant when present.
if (cause !== null) {
snapshot.cause = cause.map((entry) => ({
label: entry.label,
message: entry.message,
source: focusSource(entry.source, next),
stack: sanitizeStack(entry.stack, next) ?? [],
}))
}
return snapshot return snapshot
} }
......
...@@ -1554,6 +1554,52 @@ export async function hasRedboxCallStack(browser: Playwright) { ...@@ -1554,6 +1554,52 @@ export async function hasRedboxCallStack(browser: Playwright) {
}) })
} }
export interface RedboxCauseEntry {
label: string | null
message: string | null
source: string | null
stack: string[]
}
export async function getRedboxCause(
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 causeElements = root?.querySelectorAll('[data-nextjs-error-cause]')
if (!causeElements || causeElements.length === 0) return null
const causes: {
label: string | null
message: string | null
source: string | null
stack: string[]
}[] = []
for (const el of causeElements) {
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, ' '))
}
causes.push({
label: el.querySelector('.error-cause-label')?.innerText ?? null,
message: el.querySelector('.error-cause-message')?.innerText ?? null,
source:
el.querySelector(':scope > [data-nextjs-codeframe]')?.innerText ??
null,
stack,
})
}
return causes
})
}
export async function getRedboxCallStack( export async function getRedboxCallStack(
browser: Playwright browser: Playwright
): Promise<string[] | null> { ): Promise<string[] | null> {
...@@ -1570,6 +1616,10 @@ export async function getRedboxCallStack( ...@@ -1570,6 +1616,10 @@ 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
if (frameElement.closest('[data-nextjs-error-cause]')) {
continue
}
// `innerText` will be "${methodName}\n${location}". // `innerText` will be "${methodName}\n${location}".
// Ideally `innerText` would be "${methodName} ${location}" // Ideally `innerText` would be "${methodName} ${location}"
// so that c&p automatically does the right thing. // so that c&p automatically does the right thing.
......
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