Unverified Commit 2aa2eaad authored by Jude Gao's avatar Jude Gao Committed by GitHub

dev error overlay: async boundary for original stack frame call (#75718)

parent 3fdf51cf
......@@ -633,5 +633,7 @@
"632": "Invariant (SlowModuleDetectionPlugin): Module is missing a required debugId. This is a Next.js internal bug.",
"633": "Dynamic route not found",
"634": "Route %s used \"searchParams\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"searchParams\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"635": "%s: Invalid source map. Only conformant source maps can be used to find the original code."
"635": "%s: Invalid source map. Only conformant source maps can be used to find the original code.",
"636": "Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.",
"637": "Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js."
}
......@@ -20,19 +20,19 @@ export const Default: Story = {
id: 0,
runtime: true,
error: new Error('First error message'),
frames: [],
frames: () => Promise.resolve([]),
},
{
id: 1,
runtime: true,
error: new Error('Second error message'),
frames: [],
frames: () => Promise.resolve([]),
},
{
id: 2,
runtime: true,
error: new Error('Third error message'),
frames: [],
frames: () => Promise.resolve([]),
},
],
activeIdx: 1,
......
......@@ -20,19 +20,19 @@ const mockErrors = [
id: 1,
runtime: true as const,
error: new Error('First error'),
frames: [],
frames: () => Promise.resolve([]),
},
{
id: 2,
runtime: true as const,
error: new Error('Second error'),
frames: [],
frames: () => Promise.resolve([]),
},
{
id: 3,
runtime: true as const,
error: new Error('Third error'),
frames: [],
frames: () => Promise.resolve([]),
},
]
......
import { useCallback, useEffect, useRef, useState } from 'react'
import {
startTransition,
useCallback,
useEffect,
useRef,
useState,
} from 'react'
import { noop as css } from '../../../helpers/noop-template'
import { LeftArrow } from '../../../icons/left-arrow'
import { RightArrow } from '../../../icons/right-arrow'
......@@ -17,17 +23,23 @@ export function ErrorOverlayPagination({
}: ErrorPaginationProps) {
const handlePrevious = useCallback(
() =>
activeIdx > 0 ? onActiveIndexChange(Math.max(0, activeIdx - 1)) : null,
startTransition(() => {
if (activeIdx > 0) {
onActiveIndexChange(Math.max(0, activeIdx - 1))
}
}),
[activeIdx, onActiveIndexChange]
)
const handleNext = useCallback(
() =>
activeIdx < readyErrors.length - 1
? onActiveIndexChange(
startTransition(() => {
if (activeIdx < readyErrors.length - 1) {
onActiveIndexChange(
Math.max(0, Math.min(readyErrors.length - 1, activeIdx + 1))
)
: null,
}
}),
[activeIdx, readyErrors.length, onActiveIndexChange]
)
......
......@@ -74,74 +74,78 @@ const readyErrors: ReadyRuntimeError[] = [
id: 1,
runtime: true,
error: new Error('First error message'),
frames: [
frame,
{
...frame,
originalStackFrame: {
...frame.originalStackFrame,
methodName: 'ParentComponent',
lineNumber: 5,
frames: () =>
Promise.resolve([
frame,
{
...frame,
originalStackFrame: {
...frame.originalStackFrame,
methodName: 'ParentComponent',
lineNumber: 5,
},
},
},
{
...frame,
originalStackFrame: {
...frame.originalStackFrame,
methodName: 'GrandparentComponent',
lineNumber: 1,
{
...frame,
originalStackFrame: {
...frame.originalStackFrame,
methodName: 'GrandparentComponent',
lineNumber: 1,
},
},
},
...Array(20).fill(ignoredFrame),
],
...Array(20).fill(ignoredFrame),
]),
},
{
id: 2,
runtime: true,
error: new Error('Second error message'),
frames: [
{
error: true,
reason: 'Second error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Second error message'),
},
],
frames: () =>
Promise.resolve([
{
error: true,
reason: 'Second error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Second error message'),
},
]),
},
{
id: 3,
runtime: true,
error: new Error('Third error message'),
frames: [
{
error: true,
reason: 'Third error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Third error message'),
},
],
frames: () =>
Promise.resolve([
{
error: true,
reason: 'Third error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Third error message'),
},
]),
},
{
id: 4,
runtime: true,
error: new Error('Fourth error message'),
frames: [
{
error: true,
reason: 'Fourth error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Fourth error message'),
},
],
frames: () =>
Promise.resolve([
{
error: true,
reason: 'Fourth error message',
external: false,
ignored: false,
sourceStackFrame,
originalStackFrame,
originalCodeFrame: originalCodeFrame('Fourth error message'),
},
]),
},
]
......@@ -205,21 +209,22 @@ export const WithHydrationWarning: Story = {
},
],
}),
frames: [
{
error: true,
reason: 'First error message',
external: false,
ignored: false,
sourceStackFrame: {
file: 'app/page.tsx',
methodName: 'Home',
arguments: [],
lineNumber: 10,
column: 5,
frames: () =>
Promise.resolve([
{
error: true,
reason: 'First error message',
external: false,
ignored: false,
sourceStackFrame: {
file: 'app/page.tsx',
methodName: 'Home',
arguments: [],
lineNumber: 10,
column: 5,
},
},
},
],
]),
},
],
debugInfo: { devtoolsFrontendUrl: undefined },
......
import { useState, useMemo, useEffect, useRef } from 'react'
import { useState, useMemo, useEffect, useRef, Suspense } from 'react'
import type { DebugInfo } from '../../../types'
import { Overlay } from '../components/overlay'
import { noop as css } from '../helpers/noop-template'
......@@ -192,11 +192,13 @@ export function Errors({
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff}
/>
) : null}
<RuntimeError
key={activeError.id.toString()}
error={activeError}
dialogResizerRef={dialogResizerRef}
/>
<Suspense fallback={<div data-nextjs-error-suspended />}>
<RuntimeError
key={activeError.id.toString()}
error={activeError}
dialogResizerRef={dialogResizerRef}
/>
</Suspense>
</ErrorOverlayLayout>
)
}
......
......@@ -3,7 +3,10 @@ import { CodeFrame } from '../../components/code-frame/code-frame'
import { CallStack } from '../../components/errors/call-stack/call-stack'
import { noop as css } from '../../helpers/noop-template'
import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html'
import type { ReadyRuntimeError } from '../../../../internal/helpers/get-error-by-type'
import {
useFrames,
type ReadyRuntimeError,
} from '../../../../internal/helpers/get-error-by-type'
export type RuntimeErrorProps = {
error: ReadyRuntimeError
......@@ -11,16 +14,18 @@ export type RuntimeErrorProps = {
}
export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
const frames = useFrames(error)
const firstFrame = useMemo(() => {
const firstFirstPartyFrameIndex = error.frames.findIndex(
const firstFirstPartyFrameIndex = frames.findIndex(
(entry) =>
!entry.ignored &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
return error.frames[firstFirstPartyFrameIndex] ?? null
}, [error.frames])
return frames[firstFirstPartyFrameIndex] ?? null
}, [frames])
return (
<>
......@@ -31,8 +36,8 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
/>
)}
{error.frames.length > 0 && (
<CallStack dialogResizerRef={dialogResizerRef} frames={error.frames} />
{frames.length > 0 && (
<CallStack dialogResizerRef={dialogResizerRef} frames={frames} />
)}
</>
)
......
......@@ -76,21 +76,17 @@ export function useErrorHook({
if (nextError == null) {
return
}
let mounted = true
getErrorByType(nextError, isAppDir).then(
(resolved) => {
getErrorByType(nextError, isAppDir).then((resolved) => {
if (mounted) {
// We don't care if the desired error changed while we were resolving,
// thus we're not tracking it using a ref. Once the work has been done,
// we'll store it.
if (mounted) {
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
},
() => {
// TODO: handle this, though an edge case
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
)
})
return () => {
mounted = false
......
import { useState, useEffect, useMemo, useCallback } from 'react'
import { useState, useEffect, useMemo, useCallback, Suspense } from 'react'
import {
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
......@@ -162,21 +162,16 @@ export function Errors({
if (nextError == null) {
return
}
let mounted = true
getErrorByType(nextError, isAppDir).then(
(resolved) => {
let mounted = true
getErrorByType(nextError, isAppDir).then((resolved) => {
if (mounted) {
// We don't care if the desired error changed while we were resolving,
// thus we're not tracking it using a ref. Once the work has been done,
// we'll store it.
if (mounted) {
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
},
() => {
// TODO: handle this, though an edge case
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
)
})
return () => {
mounted = false
......@@ -401,9 +396,14 @@ export function Errors({
</div>
) : undefined}
</DialogHeader>
<DialogBody className="nextjs-container-errors-body">
<RuntimeError key={activeError.id.toString()} error={activeError} />
</DialogBody>
<Suspense fallback={<div data-nextjs-error-suspended />}>
<DialogBody className="nextjs-container-errors-body">
<RuntimeError
key={activeError.id.toString()}
error={activeError}
/>
</DialogBody>
</Suspense>
</DialogContent>
</Dialog>
</Overlay>
......
import * as React from 'react'
import { CodeFrame } from '../../components/CodeFrame'
import type { ReadyRuntimeError } from '../../helpers/get-error-by-type'
import {
useFrames,
type ReadyRuntimeError,
} from '../../helpers/get-error-by-type'
import { noop as css } from '../../helpers/noop-template'
import { CallStackFrame } from './CallStackFrame'
......@@ -8,13 +11,15 @@ export type RuntimeErrorProps = { error: ReadyRuntimeError }
export function RuntimeError({ error }: RuntimeErrorProps) {
const [isIgnoredExpanded, setIsIgnoredExpanded] = React.useState(false)
const frames = useFrames(error)
const {
firstFrame,
allLeadingFrames,
trailingCallStackFrames,
displayedFramesCount,
} = React.useMemo(() => {
const filteredFrames = error.frames.filter((frame) =>
const filteredFrames = frames.filter((frame) =>
isIgnoredExpanded ? true : !frame.ignored
)
......@@ -36,10 +41,10 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
firstFirstPartyFrameIndex < 0 ? 0 : firstFirstPartyFrameIndex
),
}
}, [error.frames, isIgnoredExpanded])
}, [frames, isIgnoredExpanded])
return (
<React.Fragment>
<>
{firstFrame ? (
<>
<h2>Source</h2>
......@@ -64,8 +69,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
))}
{
// if the default displayed ignored frames count is equal equal to the total frames count, hide the button
displayedFramesCount === error.frames.length &&
!isIgnoredExpanded ? null : (
displayedFramesCount === frames.length && !isIgnoredExpanded ? null : (
<button
data-expand-ignore-button={isIgnoredExpanded}
onClick={() => setIsIgnoredExpanded(!isIgnoredExpanded)}
......@@ -74,7 +78,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
</button>
)
}
</React.Fragment>
</>
)
}
......
......@@ -7,15 +7,38 @@ import { getOriginalStackFrames } from './stack-frame'
import type { OriginalStackFrame } from './stack-frame'
import type { ComponentStackFrame } from './parse-component-stack'
import { getErrorSource } from '../../../../../shared/lib/error-source'
import React from 'react'
export type ReadyRuntimeError = {
id: number
runtime: true
error: Error
frames: OriginalStackFrame[]
frames: OriginalStackFrame[] | (() => Promise<OriginalStackFrame[]>)
componentStackFrames?: ComponentStackFrame[]
}
export const useFrames = (error: ReadyRuntimeError): OriginalStackFrame[] => {
if ('use' in React) {
const frames = error.frames
if (typeof frames !== 'function') {
throw new Error(
'Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.'
)
}
return React.use((frames as () => Promise<OriginalStackFrame[]>)())
} else {
if (!Array.isArray(error.frames)) {
throw new Error(
'Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js.'
)
}
return error.frames
}
}
export async function getErrorByType(
ev: SupportedErrorEvent,
isAppDir: boolean
......@@ -24,20 +47,43 @@ export async function getErrorByType(
switch (event.type) {
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: {
const readyRuntimeError: ReadyRuntimeError = {
const baseError = {
id,
runtime: true,
error: event.reason,
frames: await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
} as const
if ('use' in React) {
const readyRuntimeError: ReadyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
)
}),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
} else {
const readyRuntimeError: ReadyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
}
return readyRuntimeError
}
default: {
break
......@@ -47,3 +93,12 @@ export async function getErrorByType(
const _: never = event
throw new Error('type system invariant violation')
}
function createMemoizedPromise<T>(
promiseFactory: () => Promise<T>
): () => Promise<T> {
const cachedPromise = promiseFactory()
return function (): Promise<T> {
return cachedPromise
}
}
......@@ -6,6 +6,7 @@ import {
describeVariants as describe,
getStackFramesContent,
retry,
getRedboxCallStack,
} from 'next-test-utils'
import path from 'path'
import { outdent } from 'outdent'
......@@ -793,6 +794,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toContain('app/page.js')
expect(source).toContain(`throw new Error('Client error')`)
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......@@ -830,6 +833,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toContain('app/page.js')
expect(source).toContain(`throw new Error('Server error')`)
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......@@ -876,6 +881,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toMatchSnapshot()
}
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......@@ -934,6 +941,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toMatchSnapshot()
}
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
......@@ -5,6 +5,7 @@ import {
describeVariants as describe,
getStackFramesContent,
toggleCollapseCallStackFrames,
hasRedboxCallStack,
} from 'next-test-utils'
import path from 'path'
import { outdent } from 'outdent'
......@@ -764,6 +765,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
await hasRedboxCallStack(browser)
const callStackFrames = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox, getRedboxSource } from 'next-test-utils'
import {
assertHasRedbox,
getRedboxSource,
hasRedboxCallStack,
} from 'next-test-utils'
import { outdent } from 'outdent'
function normalizeStackTrace(trace) {
......@@ -24,6 +28,7 @@ describe('app dir - dynamic error trace', () => {
)
).resolves.toEqual(false)
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
import { nextTestSetup } from 'e2e-utils'
import { getRedboxSource, openRedbox } from 'next-test-utils'
import {
getRedboxSource,
openRedbox,
hasRedboxCallStack,
} from 'next-test-utils'
// TODO: When owner stack is enabled by default, remove the condition and only keep one test
const isOwnerStackEnabled = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
async function getStackFramesContent(browser) {
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
......@@ -4,6 +4,7 @@ import {
assertNoRedbox,
openRedbox,
getRedboxDescription,
hasRedboxCallStack,
} from 'next-test-utils'
// TODO: parse the location and assert them in the future
......@@ -18,6 +19,7 @@ function normalizeStackTrace(trace: string) {
}
async function getStackFramesContent(browser) {
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
......@@ -825,6 +825,21 @@ export async function retry<T>(
}
}
async function ensureNoSuspendedComponentsInRedBox(browser: BrowserInterface) {
await retry(async () => {
const suspended = await browser.eval(() => {
return Boolean(
[].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector('[data-nextjs-error-suspended]')
)
)
})
expect(suspended).toBe(false)
}, 10000)
}
export async function assertHasRedbox(browser: BrowserInterface) {
try {
await retry(
......@@ -845,6 +860,8 @@ export async function assertHasRedbox(browser: BrowserInterface) {
5000,
200
)
await ensureNoSuspendedComponentsInRedBox(browser)
} catch (errorCause) {
const error = new Error('Expected Redbox but found none')
Error.captureStackTrace(error, assertHasRedbox)
......@@ -1014,7 +1031,9 @@ export async function getRedboxTotalErrorCount(browser: BrowserInterface) {
return parseInt(header.match(/\d+ of (\d+) issue/)?.[1], 10)
}
export function getRedboxSource(browser: BrowserInterface) {
export async function getRedboxSource(browser: BrowserInterface) {
await ensureNoSuspendedComponentsInRedBox(browser)
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
......@@ -1330,6 +1349,7 @@ export async function toggleCollapseComponentStack(
}
export async function hasRedboxCallStack(browser: BrowserInterface) {
await ensureNoSuspendedComponentsInRedBox(browser)
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
......@@ -1343,8 +1363,7 @@ export async function hasRedboxCallStack(browser: BrowserInterface) {
export async function getRedboxCallStack(
browser: BrowserInterface
): Promise<string | null> {
await browser.waitForElementByCss('[data-nextjs-call-stack-frame]', 30000)
await ensureNoSuspendedComponentsInRedBox(browser)
const callStackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......@@ -1358,8 +1377,7 @@ export async function getRedboxCallStack(
export async function getRedboxCallStackCollapsed(
browser: BrowserInterface
): Promise<string> {
await browser.waitForElementByCss('.nextjs-container-errors-body', 30000)
await ensureNoSuspendedComponentsInRedBox(browser)
const callStackFrameElements = await browser.elementsByCss(
'.nextjs-container-errors-body > [data-nextjs-codeframe] > :first-child, ' +
'.nextjs-container-errors-body > [data-nextjs-call-stack-frame], ' +
......@@ -1581,6 +1599,7 @@ export const checkLink = (
) => checkMeta(browser, rel, content, 'rel', 'link', 'href')
export async function getStackFramesContent(browser) {
await ensureNoSuspendedComponentsInRedBox(browser)
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......
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