Unverified Commit 064970e0 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

feat: stitch errors with react owner stack (#70393)

parent 6fba7b24
......@@ -561,6 +561,7 @@ pub struct ExperimentalConfig {
/// directory.
ppr: Option<ExperimentalPartialPrerendering>,
taint: Option<bool>,
react_owner_stack: Option<bool>,
#[serde(rename = "dynamicIO")]
dynamic_io: Option<bool>,
proxy_timeout: Option<f64>,
......@@ -1148,6 +1149,13 @@ impl NextConfig {
Vc::cell(self.experimental.taint.unwrap_or(false))
}
#[turbo_tasks::function]
pub async fn enable_react_owner_stack(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(
self.await?.experimental.react_owner_stack.unwrap_or(false),
))
}
#[turbo_tasks::function]
pub fn use_swc_css(&self) -> Vc<bool> {
Vc::cell(
......
......@@ -116,12 +116,14 @@ pub async fn get_next_client_import_map(
match ty.into_value() {
ClientContextType::Pages { .. } => {}
ClientContextType::App { app_dir } => {
let react_flavor =
if *next_config.enable_ppr().await? || *next_config.enable_taint().await? {
"-experimental"
} else {
""
};
let react_flavor = if *next_config.enable_ppr().await?
|| *next_config.enable_taint().await?
|| *next_config.enable_react_owner_stack().await?
{
"-experimental"
} else {
""
};
import_map.insert_exact_alias(
"react",
......@@ -683,7 +685,12 @@ async fn rsc_aliases(
) -> Result<()> {
let ppr = *next_config.enable_ppr().await?;
let taint = *next_config.enable_taint().await?;
let react_channel = if ppr || taint { "-experimental" } else { "" };
let react_owner_stack = *next_config.enable_react_owner_stack().await?;
let react_channel = if ppr || taint || react_owner_stack {
"-experimental"
} else {
""
};
let react_client_package = get_react_client_package(&next_config).await?;
let mut alias = FxIndexMap::default();
......
......@@ -185,6 +185,9 @@ export function getDefineEnv({
),
'process.env.__NEXT_PPR': checkIsAppPPREnabled(config.experimental.ppr),
'process.env.__NEXT_DYNAMIC_IO': !!config.experimental.dynamicIO,
'process.env.__NEXT_REACT_OWNER_STACK': Boolean(
config.experimental.reactOwnerStack
),
'process.env.__NEXT_AFTER': config.experimental.after ?? false,
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': fetchCacheKeyPrefix ?? '',
......
......@@ -9,7 +9,11 @@ import React, { use } from 'react'
// eslint-disable-next-line import/no-extraneous-dependencies
import { createFromReadableStream } from 'react-server-dom-webpack/client'
import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'
import { onRecoverableError } from './on-recoverable-error'
import { onRecoverableError } from './react-client-callbacks/shared'
import {
onCaughtError,
onUncaughtError,
} from './react-client-callbacks/app-router'
import { callServer } from './app-call-server'
import { findSourceMapURL } from './app-find-source-map-url'
import {
......@@ -23,6 +27,8 @@ import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runt
/// <reference types="react-dom/experimental" />
const isReactOwnerStackEnabled = !!process.env.__NEXT_REACT_OWNER_STACK
const appElement: HTMLElement | Document | null = document
const encoder = new TextEncoder()
......@@ -227,8 +233,17 @@ export function hydrate() {
const rootLayoutMissingTags = window.__next_root_layout_missing_tags
const hasMissingTags = !!rootLayoutMissingTags?.length
const errorCallbacks =
isReactOwnerStackEnabled && process.env.NODE_ENV !== 'production'
? {
onCaughtError,
onUncaughtError,
}
: undefined
const options = {
onRecoverableError,
...errorCallbacks,
} satisfies ReactDOMClient.RootOptions
const isError =
document.documentElement.id === '__next_error__' || hasMissingTags
......
......@@ -2,7 +2,7 @@ import isError from '../../../lib/is-error'
import { isNextRouterError } from '../is-next-router-error'
import { handleClientError } from '../react-dev-overlay/internal/helpers/use-error-handler'
const originConsoleError = window.console.error
export const originConsoleError = window.console.error
// Patch console.error to collect information about hydration errors
export function patchConsoleError() {
......
import * as React from 'react'
import React from 'react'
import { ACTION_UNHANDLED_ERROR, type OverlayState } from '../shared'
import { ShadowPortal } from '../internal/components/ShadowPortal'
import { BuildError } from '../internal/container/BuildError'
import { Errors } from '../internal/container/Errors'
import { StaticIndicator } from '../internal/container/StaticIndicator'
import type { SupportedErrorEvent } from '../internal/container/Errors'
import { Errors, type SupportedErrorEvent } from '../internal/container/Errors'
import { parseStack } from '../internal/helpers/parse-stack'
import { StaticIndicator } from '../internal/container/StaticIndicator'
import { Base } from '../internal/styles/Base'
import { ComponentStyles } from '../internal/styles/ComponentStyles'
import { CssReset } from '../internal/styles/CssReset'
import { RootLayoutMissingTagsError } from '../internal/container/root-layout-missing-tags-error'
import type { Dispatcher } from './hot-reloader-client'
import { RuntimeErrorHandler } from '../internal/helpers/runtime-error-handler'
interface ReactDevOverlayState {
reactError: SupportedErrorEvent | null
......@@ -21,7 +20,6 @@ export default class ReactDevOverlay extends React.PureComponent<
state: OverlayState
dispatcher?: Dispatcher
children: React.ReactNode
onReactError: (error: Error) => void
},
ReactDevOverlayState
> {
......@@ -29,6 +27,8 @@ export default class ReactDevOverlay extends React.PureComponent<
static getDerivedStateFromError(error: Error): ReactDevOverlayState {
if (!error.stack) return { reactError: null }
RuntimeErrorHandler.hadRuntimeError = true
return {
reactError: {
id: 0,
......@@ -41,10 +41,6 @@ export default class ReactDevOverlay extends React.PureComponent<
}
}
componentDidCatch(componentErr: Error) {
this.props.onReactError(componentErr)
}
render() {
const { state, children, dispatcher } = this.props
const { reactError } = this.state
......@@ -79,20 +75,11 @@ export default class ReactDevOverlay extends React.PureComponent<
/>
) : (
<>
{reactError ? (
<Errors
isAppDir={true}
versionInfo={state.versionInfo}
initialDisplayState="fullscreen"
errors={[reactError]}
hasStaticIndicator={hasStaticIndicator}
debugInfo={debugInfo}
/>
) : hasRuntimeErrors ? (
{hasRuntimeErrors ? (
<Errors
isAppDir={true}
initialDisplayState="minimized"
errors={state.errors}
initialDisplayState={reactError ? 'fullscreen' : 'minimized'}
errors={reactError ? [reactError] : state.errors}
versionInfo={state.versionInfo}
hasStaticIndicator={hasStaticIndicator}
debugInfo={debugInfo}
......
......@@ -37,6 +37,7 @@ import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import type { HydrationErrorState } from '../internal/helpers/hydration-error-info'
import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked'
import { getReactStitchedError } from '../internal/helpers/stitched-error'
export interface Dispatcher {
onBuildOk(): void
......@@ -563,10 +564,12 @@ export default function HotReload({
const componentStackTrace =
(error as any)._componentStack || errorDetails?.componentStack
const warning = errorDetails?.warning
const stitchedError = getReactStitchedError(error)
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack),
reason: stitchedError,
frames: parseStack(stitchedError.stack || ''),
componentStackFrames:
typeof componentStackTrace === 'string'
? parseComponentStack(componentStackTrace)
......@@ -576,19 +579,18 @@ export default function HotReload({
},
[dispatch]
)
const handleOnUnhandledRejection = useCallback(
(reason: Error): void => {
const stitchedError = getReactStitchedError(reason)
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(reason.stack!),
reason: stitchedError,
frames: parseStack(stitchedError.stack || ''),
})
},
[dispatch]
)
const handleOnReactError = useCallback(() => {
RuntimeErrorHandler.hadRuntimeError = true
}, [])
useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection)
const webSocketRef = useWebsocket(assetPrefix)
......@@ -674,11 +676,7 @@ export default function HotReload({
])
return (
<ReactDevOverlay
onReactError={handleOnReactError}
state={state}
dispatcher={dispatcher}
>
<ReactDevOverlay state={state} dispatcher={dispatcher}>
{children}
</ReactDevOverlay>
)
......
......@@ -42,7 +42,6 @@ export function createDevOverlayElement(reactEl: React.ReactElement) {
<FallbackLayout>
<ReactDevOverlay
state={{ ...INITIAL_OVERLAY_STATE, rootLayoutMissingTags }}
onReactError={() => {}}
>
{reactEl}
</ReactDevOverlay>
......
......@@ -31,7 +31,7 @@ import {
} from '../helpers/hydration-error-info'
import { NodejsInspectorCopyButton } from '../components/nodejs-inspector'
import { CopyButton } from '../components/copy-button'
import { ConsoleError } from '../helpers/console-error'
import { isUnhandledConsoleOrRejection } from '../helpers/console-error'
export type SupportedErrorEvent = {
id: number
......@@ -61,11 +61,11 @@ function ErrorDescription({
error: Error
hydrationWarning: string | null
}) {
const isFromConsoleError = error instanceof ConsoleError
const isUnhandledError = isUnhandledConsoleOrRejection(error)
// If there's hydration warning or console error, skip displaying the error name
return (
<>
{isFromConsoleError || hydrationWarning ? '' : error.name + ': '}
{isUnhandledError || hydrationWarning ? '' : error.name + ': '}
<HotlinkedText
text={hydrationWarning || error.message}
matcher={isNextjsLink}
......@@ -257,8 +257,7 @@ export function Errors({
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(error) || ''
)
const isFromConsoleError = error instanceof ConsoleError
const isUnhandledError = isUnhandledConsoleOrRejection(error)
const errorDetails: HydrationErrorState = (error as any).details || {}
const notes = errorDetails.notes || ''
const [warningTemplate, serverContent, clientContent] =
......@@ -308,7 +307,7 @@ export function Errors({
>
{isServerError
? 'Server Error'
: isFromConsoleError
: isUnhandledError
? 'Console Error'
: 'Unhandled Runtime Error'}
</h1>
......
export class ConsoleError extends Error {
constructor(message: string) {
super(message)
this.name = 'ConsoleError'
}
// Represent non Error shape unhandled promise rejections or console.error errors.
// Those errors will be captured and displayed in Error Overlay.
type UnhandledError = Error & { digest: 'NEXT_UNHANDLED_ERROR' }
export function createUnhandledError(message: string): UnhandledError {
const error = new Error(message) as UnhandledError
error.digest = 'NEXT_UNHANDLED_ERROR'
return error
}
export const isUnhandledConsoleOrRejection = (
error: any
): error is UnhandledError => {
return error && error.digest === 'NEXT_UNHANDLED_ERROR'
}
......@@ -72,6 +72,7 @@ export function parseComponentStack(
): ComponentStackFrame[] {
const componentStackFrames: ComponentStackFrame[] = []
for (const line of componentStack.trim().split('\n')) {
// TODO: support safari stack trace
// Get component and file from the component stack line
const match = /at ([^ ]+)( \((.*)\))?/.exec(line)
if (match?.[1]) {
......
import React from 'react'
import isError from '../../../../../lib/is-error'
const captureOwnerStack = (React as any).captureOwnerStack || (() => '')
const REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame'
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp(
`(at ${REACT_ERROR_STACK_BOTTOM_FRAME} )|(${REACT_ERROR_STACK_BOTTOM_FRAME}\\@)`
)
export function getReactStitchedError<T = unknown>(err: T): Error | T {
if (!process.env.__NEXT_REACT_OWNER_STACK) {
return err
}
const isErrorInstance = isError(err)
const originStack = isErrorInstance ? err.stack || '' : ''
const originMessage = isErrorInstance ? err.message : ''
const stackLines = originStack.split('\n')
const indexOfSplit = stackLines.findIndex((line) =>
REACT_ERROR_STACK_BOTTOM_FRAME_REGEX.test(line)
)
const isOriginalReactError = indexOfSplit >= 0 // has the react-stack-bottom-frame
let newStack = isOriginalReactError
? stackLines.slice(0, indexOfSplit).join('\n')
: originStack
const newError = new Error(originMessage)
// Copy all enumerable properties, e.g. digest
Object.assign(newError, err)
newError.stack = newStack
// Avoid duplicate overriding stack frames
const ownerStack = captureOwnerStack()
if (ownerStack && newStack.endsWith(ownerStack) === false) {
newStack += ownerStack
// Override stack
newError.stack = newStack
}
return newError
}
......@@ -4,7 +4,7 @@ import { isNextRouterError } from '../../../is-next-router-error'
import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info'
import { formatConsoleArgs } from '../../../../lib/console'
import isError from '../../../../../lib/is-error'
import { ConsoleError } from './console-error'
import { createUnhandledError } from './console-error'
import { enqueueConsecutiveDedupedError } from './enqueue-client-error'
export type ErrorHandler = (error: Error) => void
......@@ -22,7 +22,7 @@ export function handleClientError(
if (!originError || !isError(originError)) {
// If it's not an error, format the args into an error
const formattedErrorMessage = formatConsoleArgs(consoleErrorArgs)
error = new ConsoleError(formattedErrorMessage)
error = createUnhandledError(formattedErrorMessage)
} else {
error = originError
}
......@@ -60,6 +60,32 @@ export function useErrorHandler(
}, [handleOnUnhandledError, handleOnUnhandledRejection])
}
function onUnhandledError(event: WindowEventMap['error']): void | boolean {
if (isNextRouterError(event.error)) {
event.preventDefault()
return false
}
handleClientError(event.error, [])
}
function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void {
const reason = ev?.reason
if (isNextRouterError(reason)) {
ev.preventDefault()
return
}
let error = reason
if (error && !isError(error)) {
error = createUnhandledError(error + '')
}
rejectionQueue.push(error)
for (const handler of rejectionHandlers) {
handler(error)
}
}
export function handleGlobalErrors() {
if (typeof window !== 'undefined') {
try {
......@@ -67,41 +93,7 @@ export function handleGlobalErrors() {
Error.stackTraceLimit = 50
} catch {}
window.addEventListener(
'error',
(event: WindowEventMap['error']): void | boolean => {
if (isNextRouterError(event.error)) {
event.preventDefault()
return false
}
handleClientError(event.error, [])
}
)
window.addEventListener(
'unhandledrejection',
(ev: WindowEventMap['unhandledrejection']): void => {
const reason = ev?.reason
if (isNextRouterError(reason)) {
ev.preventDefault()
return
}
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const e = reason
rejectionQueue.push(e)
for (const handler of rejectionHandlers) {
handler(e)
}
}
)
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
}
}
/* global location */
// imports polyfill from `@next/polyfill-module` after build.
import '../build/polyfills/polyfill-module'
import type Router from '../shared/lib/router/router'
import type {
AppComponent,
......@@ -46,7 +45,7 @@ import {
SearchParamsContext,
PathParamsContext,
} from '../shared/lib/hooks-client-context.shared-runtime'
import { onRecoverableError } from './on-recoverable-error'
import { onRecoverableError } from './react-client-callbacks/shared'
import tracer from './tracing/tracer'
import reportToSocket from './tracing/report-to-socket'
......
import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'
// x-ref: https://github.com/facebook/react/blob/d4bc16a7d69eb2ea38a88c8ac0b461d5f72cdcab/packages/react-dom/src/client/ReactDOMRoot.js#L83
const defaultOnRecoverableError =
typeof reportError === 'function'
? // In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError
: (error: any) => {
window.console.error(error)
}
export function onRecoverableError(
err: unknown,
errorInfo: { componentStack?: string }
) {
// In development mode, pass along the component stack to the error
if (process.env.NODE_ENV === 'development' && errorInfo.componentStack) {
;(err as any)._componentStack = errorInfo.componentStack
}
// Using default react onRecoverableError
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err)) return
defaultOnRecoverableError(err)
}
// This file is only used in app router due to the specific error state handling.
import type { HydrationOptions } from 'react-dom/client'
import { getReactStitchedError } from '../components/react-dev-overlay/internal/helpers/stitched-error'
import { handleClientError } from '../components/react-dev-overlay/internal/helpers/use-error-handler'
import { isNextRouterError } from '../components/is-next-router-error'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { reportGlobalError } from './report-global-error'
import isError from '../../lib/is-error'
import { originConsoleError } from '../components/globals/intercept-console-error'
export const onCaughtError: HydrationOptions['onCaughtError'] = (
err,
errorInfo
) => {
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err) || isNextRouterError(err)) return
const stitchedError = getReactStitchedError(err)
if (process.env.NODE_ENV === 'development') {
const errorBoundaryComponent = errorInfo?.errorBoundary?.constructor
const errorBoundaryName =
// read react component displayName
(errorBoundaryComponent as any)?.displayName ||
errorBoundaryComponent?.name ||
'Unknown'
const componentThatErroredFrame = errorInfo?.componentStack?.split('\n')[1]
// Match chrome or safari stack trace
const matches =
// regex to match the function name in the stack trace
// example 1: at Page (http://localhost:3000/_next/static/chunks/pages/index.js?ts=1631600000000:2:1)
// example 2: Page@http://localhost:3000/_next/static/chunks/pages/index.js?ts=1631600000000:2:1
componentThatErroredFrame?.match(/\s+at (\w+)\s+|(\w+)@/) ?? []
const componentThatErroredName = matches[1] || matches[2] || 'Unknown'
// In development mode, pass along the component stack to the error
if (process.env.NODE_ENV === 'development' && errorInfo.componentStack) {
;(stitchedError as any)._componentStack = errorInfo.componentStack
}
// Create error location with errored component and error boundary, to match the behavior of default React onCaughtError handler.
const errorBoundaryMessage = `It was handled by the <${errorBoundaryName}> error boundary.`
const componentErrorMessage = componentThatErroredName
? `The above error occurred in the <${componentThatErroredName}> component.`
: `The above error occurred in one of your components.`
const errorLocation = `${componentErrorMessage} ${errorBoundaryMessage}`
const originErrorStack = isError(err) ? err.stack || '' : ''
// Log the modified error message with stack so without being intercepted again.
originConsoleError(originErrorStack + '\n\n' + errorLocation)
handleClientError(stitchedError, [])
} else {
originConsoleError(err)
}
}
export const onUncaughtError: HydrationOptions['onUncaughtError'] = (
err,
errorInfo
) => {
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err) || isNextRouterError(err)) return
const stitchedError = getReactStitchedError(err)
if (process.env.NODE_ENV === 'development') {
const componentThatErroredFrame = errorInfo?.componentStack?.split('\n')[1]
// Match chrome or safari stack trace
const matches =
componentThatErroredFrame?.match(/\s+at (\w+)\s+|(\w+)@/) ?? []
const componentThatErroredName = matches[1] || matches[2] || 'Unknown'
// In development mode, pass along the component stack to the error
if (process.env.NODE_ENV === 'development' && errorInfo.componentStack) {
;(stitchedError as any)._componentStack = errorInfo.componentStack
}
// Create error location with errored component and error boundary, to match the behavior of default React onCaughtError handler.
const errorLocation = componentThatErroredName
? `The above error occurred in the <${componentThatErroredName}> component.`
: `The above error occurred in one of your components.`
const errStack = (stitchedError as any).stack || ''
// Log the modified error message with stack so without being intercepted again.
originConsoleError(errStack + '\n\n' + errorLocation)
reportGlobalError(stitchedError)
} else {
reportGlobalError(err)
}
}
export const reportGlobalError =
typeof reportError === 'function'
? // In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError
: (error: unknown) => {
window.console.error(error)
}
// This module can be shared between both pages router and app router
import type { HydrationOptions } from 'react-dom/client'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { reportGlobalError } from './report-global-error'
import { getReactStitchedError } from '../components/react-dev-overlay/internal/helpers/stitched-error'
export const onRecoverableError: HydrationOptions['onRecoverableError'] = (
err,
errorInfo
) => {
const stitchedError = getReactStitchedError(err)
// In development mode, pass along the component stack to the error
if (process.env.NODE_ENV === 'development' && errorInfo.componentStack) {
;(stitchedError as any)._componentStack = errorInfo.componentStack
}
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err)) return
reportGlobalError(stitchedError)
}
import type { NextConfig } from '../server/config-shared'
export function needsExperimentalReact(config: NextConfig) {
return Boolean(config.experimental?.ppr || config.experimental?.taint)
const { ppr, taint, reactOwnerStack } = config.experimental || {}
return Boolean(ppr || taint || reactOwnerStack)
}
......@@ -333,6 +333,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.readonly()
.optional(),
taint: z.boolean().optional(),
reactOwnerStack: z.boolean().optional(),
prerenderEarlyExit: z.boolean().optional(),
proxyTimeout: z.number().gte(0).optional(),
scrollRestoration: z.boolean().optional(),
......
......@@ -462,6 +462,12 @@ export interface ExperimentalConfig {
*/
taint?: boolean
/**
* Enables leveraging experimental captureOwnerStack API in React,
* to create a better stack trace for React errors.
*/
reactOwnerStack?: boolean
serverActions?: {
/**
* Allows adjusting body parser size limit for server actions.
......@@ -1141,6 +1147,7 @@ export const defaultConfig: NextConfig = {
process.env.__NEXT_TEST_MODE &&
process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
),
reactOwnerStack: false,
webpackBuildWorker: undefined,
webpackMemoryOptimizations: false,
optimizeServerReact: true,
......
......@@ -4,7 +4,6 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import {
check,
describeVariants as describe,
expandCallStack,
getRedboxCallStackCollapsed,
retry,
} from 'next-test-utils'
......@@ -777,7 +776,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
await cleanup()
})
test('Call stack count for client error', async () => {
test('Call stack for client error', async () => {
const { session, browser, cleanup } = await sandbox(
next,
new Map([
......@@ -796,25 +795,30 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
])
)
await session.assertHasRedbox()
await expandCallStack(browser)
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const callStackFrames = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
try {
await session.assertHasRedbox()
expect(callStackFrames.length).toBeGreaterThan(9)
// Should still show the errored line in source code
const source = await session.getRedboxSource()
expect(source).toContain('app/page.js')
expect(source).toContain(`throw new Error('Client error')`)
const moduleGroup = await browser.elementsByCss(
'[data-nextjs-collapsed-call-stack-details]'
)
// Expect some of the call stack frames to be grouped (by React or Next.js)
expect(moduleGroup.length).toBeGreaterThan(0)
await expect(
browser.hasElementByCssSelector(
'[data-nextjs-data-runtime-error-collapsed-action]'
)
).resolves.toEqual(false)
await cleanup()
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
const stackFrames = (
await Promise.all(stackFrameElements.map((f) => f.innerText()))
).filter(Boolean)
expect(stackFrames).toEqual([])
} finally {
await cleanup()
}
})
test('Call stack for server error', async () => {
......@@ -849,20 +853,10 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
const stackFrames = await Promise.all(
stackFrameElements.map((f) => f.innerText())
)
expect(stackFrames).toEqual(
// TODO: Show useful stack
[
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
'',
'',
'',
'',
]
)
const stackFrames = (
await Promise.all(stackFrameElements.map((f) => f.innerText()))
).filter(Boolean)
expect(stackFrames).toEqual([])
} finally {
await cleanup()
}
......
/* eslint-env jest */
import { sandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { describeVariants as describe, expandCallStack } from 'next-test-utils'
import { describeVariants as describe } from 'next-test-utils'
import path from 'path'
import { outdent } from 'outdent'
......@@ -765,8 +765,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
await session.assertHasRedbox()
await expandCallStack(browser)
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const callStackFrames = await browser.elementsByCss(
......@@ -805,7 +803,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
)
await session.assertHasRedbox()
await expandCallStack(browser)
let callStackFrames = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
......@@ -835,7 +832,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
)
await session.assertHasRedbox()
await expandCallStack(browser)
// Should still show the errored line in source code
const source = await session.getRedboxSource()
......
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
shouldRunTurboDevTest,
getRedboxSource,
} from 'next-test-utils'
import { assertHasRedbox, getRedboxSource } from 'next-test-utils'
import { outdent } from 'outdent'
const isReactExperimental = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
function normalizeStackTrace(trace) {
return trace.replace(/ \(.*\)/g, '')
}
describe('app dir - dynamic error trace', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies: {
swr: 'latest',
},
packageJson: {
scripts: {
build: 'next build',
dev: `next ${shouldRunTurboDevTest() ? 'dev --turbo' : 'dev'}`,
start: 'next start',
},
},
installCommand: 'pnpm install',
startCommand: (global as any).isNextDev ? 'pnpm dev' : 'pnpm start',
buildCommand: 'pnpm build',
skipDeployment: true,
})
if (skipped) return
......@@ -40,20 +29,15 @@ describe('app dir - dynamic error trace', () => {
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
const stackFrames = await Promise.all(
// TODO: Why is this text empty?
stackFrameElements.map((f) => f.innerText())
)
expect(stackFrames).toEqual(
// TODO: Show useful stack
[
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
'',
'',
'',
'',
]
const stackFramesContent = // TODO: Why is this text empty?
(await Promise.all(stackFrameElements.map((f) => f.innerText())))
// Filter out the frames having code snippet but without methodName and source
.filter(Boolean)
.join('\n')
// TODO: Show useful stack
expect(normalizeStackTrace(stackFramesContent)).toMatchInlineSnapshot(
isReactExperimental ? `""` : `""`
)
const codeframe = await getRedboxSource(browser)
......
'use client'
import { Component } from 'react'
class MyErrorBoundary extends Component {
static getDerivedStateFromError(error) {
return { error }
}
state = { error: null }
render() {
if (this.state.error) {
return 'failed'
}
return this.props.children
}
}
function Inner() {
return (
<MyErrorBoundary>
<Thrower />
</MyErrorBoundary>
)
}
function Thrower() {
useErrorHook()
}
function useThrowError() {
if (typeof window !== 'undefined') {
throw new Error('browser error')
}
}
function useErrorHook() {
useThrowError()
}
export default function Page() {
return <Inner />
}
'use client'
function useThrowError() {
if (typeof window !== 'undefined') {
Promise.reject('string in rejected promise')
}
}
function useErrorHook() {
useThrowError()
}
export default function Page() {
useErrorHook()
return <p>hello world</p>
}
'use client'
function useThrowError() {
if (typeof window !== 'undefined') {
throw new Error('browser error')
}
}
function useErrorHook() {
useThrowError()
}
export default function Page() {
useErrorHook()
return <p>hello world</p>
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
function useThrowError() {
throw new Error('ssr error')
}
function useErrorHook() {
useThrowError()
}
export default function Page() {
useErrorHook()
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
reactOwnerStack: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
assertNoRedbox,
waitForAndOpenRuntimeError,
getRedboxDescription,
} from 'next-test-utils'
// TODO: parse the location and assert them in the future
// Remove the location `()` part in every line of stack trace;
// Remove the leading spaces in every line of stack trace;
// Remove the trailing spaces in every line of stack trace;
function normalizeStackTrace(trace: string) {
return trace
.replace(/\(.*\)/g, '')
.replace(/^\s+/gm, '')
.trim()
}
async function getStackFramesContent(browser) {
const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]'
)
const stackFramesContent = (
await Promise.all(
stackFrameElements.map(async (frame) => {
const functionNameEl = await frame.$('[data-nextjs-frame-expanded]')
const sourceEl = await frame.$('[data-has-source]')
const functionName = functionNameEl
? await functionNameEl.innerText()
: ''
const source = sourceEl ? await sourceEl.innerText() : ''
if (!functionName) {
return ''
}
return `at ${functionName} (${source})`
})
)
)
.filter(Boolean)
.join('\n')
return stackFramesContent
}
describe('app-dir - owner-stack', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should log stitched error for browser uncaught errors', async () => {
const browser = await next.browser('/browser/uncaught')
await assertHasRedbox(browser)
const stackFramesContent = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useErrorHook (app/browser/uncaught/page.js (10:3))
at Page (app/browser/uncaught/page.js (14:3))"
`)
} else {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useThrowError (app/browser/uncaught/page.js (10:3))
at useErrorHook (app/browser/uncaught/page.js (14:3))"
`)
}
const logs = await browser.log()
const errorLog = logs.find((log) => {
return log.message.includes('Error: browser error')
}).message
if (process.env.TURBOPACK) {
expect(normalizeStackTrace(errorLog)).toMatchInlineSnapshot(`
"Error: browser error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`)
} else {
expect(normalizeStackTrace(errorLog)).toMatchInlineSnapshot(`
"Error: browser error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`)
}
})
it('should log stitched error for browser caught errors', async () => {
const browser = await next.browser('/browser/caught')
await assertNoRedbox(browser)
const logs = await browser.log()
const errorLog = logs.find((log) => {
return log.message.includes('Error: browser error')
}).message
await waitForAndOpenRuntimeError(browser)
const stackFramesContent = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useErrorHook (app/browser/caught/page.js (39:3))
at Thrower (app/browser/caught/page.js (29:3))
at Inner (app/browser/caught/page.js (23:7))
at Page (app/browser/caught/page.js (43:10))"
`)
} else {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useThrowError (app/browser/caught/page.js (39:3))
at useErrorHook (app/browser/caught/page.js (29:3))
at Thrower (app/browser/caught/page.js (23:8))
at Inner (app/browser/caught/page.js (43:11))"
`)
}
expect(normalizeStackTrace(errorLog)).toMatchInlineSnapshot(`
"Error: browser error
at useThrowError
at useErrorHook
at Thrower
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Thrower> component. It was handled by the <MyErrorBoundary> error boundary."
`)
})
it('should log stitched error for SSR errors', async () => {
const browser = await next.browser('/ssr')
await assertHasRedbox(browser)
const stackFramesContent = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useErrorHook (app/ssr/page.js (8:3))
at Page (app/ssr/page.js (12:3))"
`)
} else {
expect(stackFramesContent).toMatchInlineSnapshot(`
"at useThrowError (app/ssr/page.js (8:3))
at useErrorHook (app/ssr/page.js (12:3))"
`)
}
const logs = await browser.log()
const errorLog = logs.find((log) => {
return log.message.includes('Error: ssr error')
}).message
expect(normalizeStackTrace(errorLog)).toMatchInlineSnapshot(`
"Error: ssr error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`)
})
it('should capture unhandled promise rejections', async () => {
const browser = await next.browser('/browser/reject-promise')
await waitForAndOpenRuntimeError(browser)
await assertHasRedbox(browser)
const description = await getRedboxDescription(browser)
expect(description).toMatchInlineSnapshot(`"string in rejected promise"`)
// Promise rejection has no owner stack
const stackFramesContent = await getStackFramesContent(browser)
expect(stackFramesContent).toMatchInlineSnapshot(`""`)
})
})
......@@ -1253,15 +1253,6 @@ export async function toggleCollapseComponentStack(
.click()
}
export async function expandCallStack(
browser: BrowserInterface
): Promise<void> {
// Open full Call Stack
await browser
.elementByCss('[data-nextjs-data-runtime-error-collapsed-action]')
.click()
}
export async function getRedboxCallStack(
browser: BrowserInterface
): Promise<string> {
......
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